C# virtual 这个关键字

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# virtual 这个关键字相关的知识,希望对你有一定的参考价值。

The virtual keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class. For example, this method can be overridden by any class that inherits it:

 

public virtual double Area()   
{  
    return x * y;  
}

 You cannot use the virtual modifier with the staticabstract, private, or override modifiers. The following example shows a virtual property:

class MyBaseClass
{
    // virtual auto-implemented property. Overrides can only
    // provide specialized behavior if they implement get and set accessors.
    public virtual string Name { get; set; }

    // ordinary virtual property with backing field
    private int num;
    public virtual int Number
    {
        get { return num; }
        set { num = value; }
    }
}


class MyDerivedClass : MyBaseClass
{
    private string name;

   // Override auto-implemented property with ordinary property
   // to provide specialized accessor behavior.
    public override string Name
    {
        get
        {
            return name;
        }
        set
        {
            if (value != String.Empty)
            {
                name = value;
            }
            else
            {
                name = "Unknown";
            }
        }
    }

}

 

以上是关于C# virtual 这个关键字的主要内容,如果未能解决你的问题,请参考以下文章

C#中virtual和abstract的区别

C#中的virtula是啥?

C#基础知识:virtual方法,abstract方法,区别

C#中Abstract和Virtual

C#中Abstract和Virtual的区别

C#中virtual 方法和abstract方法的区别