在哪种情况下,我应该在c#中将方法声明为虚拟 [英] In which scenario,i should declare a method as virtual in c#

查看:118
本文介绍了在哪种情况下,我应该在c#中将方法声明为虚拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我是.net的新手所以请让我明白我的疑问。

i想知道我的情景必须将我的方法声明为virtual.otherwise它将无法正常工作。



I am new to .net so please let me clear my doubt .
i wanted to know the scenarios where i have to declare my method as virtual.otherwise it will not work.

推荐答案





定义仅当在派生类中根据其行为重写方法时才使用虚方法。例如,shape类可以有Draw方法。从Shape类派生的Circle,Rectangle类可以覆盖Draw方法。



问候,

Raghu
Hi,

Define the Virtual methods only in the case if the methods are to be overridden in the derived classes as per their behavior. For an example the shape class can have Draw method. The Circle, Rectangle classes which derived from the Shape class can override the Draw method.

Regards,
Raghu


在多态中我们有方法重载和方法覆盖。



方法重载是创建具有相同名称的新方法的过程但不同的签名。



方法覆盖是创建具有相同名称和相同签名但在派生类中的新方法的过程。 />


在方法覆盖中,你必须在基类中声明一个带有 虚拟 关键字的方法,这表明它将会被覆盖。在派生类中,重写方法应使用 覆盖 关键字。
In polymorphism we have method overloading and method overriding.

Method overloading is the process of creating new method with same name but different signature.

Method overriding is the process of creating new method with same name and same signature but in a derived class.

In method overriding you have to declare a method with virtual keyword in base class which indicates that it is going to be overridden. In derived class the overriding method should use override keyword.


class Class1
{
    public virtual int GetNumber()
    {
        return 1;
    }
}




class Class2 : Class1
{
    public override int GetNumber()
    {
        int i = base.GetNumber();
        return i + 1;
    }
}




private void button1_Click(object sender, EventArgs e)
{
    Class1 class1 = new Class1();
    Class2 class2 = new Class2();

    MessageBox.Show("GetNumber() from Class1: " + class1.GetNumber());
    MessageBox.Show("GetNumber() from Class2: " + class2.GetNumber());
}


这篇关于在哪种情况下,我应该在c#中将方法声明为虚拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆