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 static, abstract, 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关键字来声明可以被派生类覆盖的方法、属性、索引器或事件,并提供了具体的代码示例。同时强调了virtual不能与static、abstract、private或override修饰符同时使用。
1345

被折叠的 条评论
为什么被折叠?



