virtual
public virtual double Area() { return x * y; }
备注
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"; } } } }
在静态属性上使用 virtual 修饰符是错误的。 通过包括使用 override 修饰符的属性声明,可在派生类中重写虚拟继承属性。
示例
public Cylinder(double r, double h): base(r, h) {}
class TestClass { public class Shape { public const double PI = Math.PI; protected double x, y; public Shape() { } public Shape(double x, double y) { this.x = x; this.y = y; } public virtual double Area() { return x * y; } } public class Circle : Shape { public Circle(double r) : base(r, 0) { } public override double Area() { return PI * x * x; } } class Sphere : Shape { public Sphere(double r) : base(r, 0) { } public override double Area() { return 4 * PI * x * x; } } class Cylinder : Shape { public Cylinder(double r, double h) : base(r, h) { } public override double Area() { return 2 * PI * x * x + 2 * PI * x * y; } } static void Main() { double r = 3.0, h = 5.0; Shape c = new Circle(r); Shape s = new Sphere(r); Shape l = new Cylinder(r, h); // Display results: Console.WriteLine("Area of Circle = {0:F2}", c.Area()); Console.WriteLine("Area of Sphere = {0:F2}", s.Area()); Console.WriteLine("Area of Cylinder = {0:F2}", l.Area()); } } /* Output: Area of Circle = 28.27 Area of Sphere = 113.10 Area of Cylinder = 150.80 */
C# 语言规范
有关更多信息,请参见C# 语言规范。 该语言规范是 C# 语法和用法的权威资料。