virtual (C# Reference)

https://msdn.microsoft.com/en-us/library/9fkccyh4.aspx

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;
}

The implementation of a virtual member can be changed by an overriding member in a derived class.

For more information about how to use thevirtual keyword,

see Versioning with the Override and New Keywords (C# Programming Guide)

and Knowing When to Use Override and New Keywords (C# Programming Guide).

Remarks

When a virtual method is invoked, the run-time type of the object is checked for an overriding member.

The overriding member in the most derived class is called, which might be the original member, if no derived class has overridden the member.

By default, methods are non-virtual. You cannot override a non-virtual method.

You cannot use the virtual modifier with the staticabstract, private, or override modifiers.

The following example shows a virtual property:

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

        private int number;
        /// <summary>
        /// ordinary virtual property with backing field
        /// </summary>
        public virtual int Number
        {
            get { return number; }
            set { number = value; }
        }
    }

    public class MyDerivedClass : MyBaseClass
    {
        private string name;
        /// <summary>
        /// Override auto-implemented property with ordinary property to provide specialized accessor behavior.
        /// </summary>
        public override string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value.Equals(string.Empty) == false ? value : "Unknown";
            }
        }
    }

Virtual properties behave like abstract methods, except for the differences in declaration and invocation调用 syntax.

  • It is an error to use the virtual modifier on a static property.
  • A virtual inherited property can be overridden in a derived class by including a property declaration that uses the override modifier.

Example

In this example, the Shape class contains the two coordinates x, y, and the Area() virtual method.

Different shape classes such as Circle, Cylinder, and Sphere inherit the Shape class, and the surface area is calculated for each figure.

Each derived class has it own override implementation ofArea().

Notice that the inherited classes Circle, Sphere, and Cylinder all use constructors that initialize the base class, as shown in the following declaration.

public Cylinder(double r, double h): base(r, h) {}

The following program calculates and displays the appropriate area for each figure by invoking the appropriate implementation of the Area()method, according to the object that is associated with the method.

 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;
            }
        }

        /// <summary>
        /// yuan
        /// </summary>
        public class Circle : Shape
        {
            public Circle(double r) : base(r, 0)
            {
            }

            public override double Area()
            {
                return PI * x * x;
            }
        }

        /// <summary>
        /// 球体
        /// </summary>
        class Sphere : Shape
        {
            public Sphere(double r) : base(r, 0)
            {
            }

            public override double Area()
            {
                return 4 * PI * x * x;
            }
        }

        /// <summary>
        /// 圆柱体
        /// </summary>
        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 Method()
        {
            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());
        }
    }
时间: 2024-08-10 15:09:48

virtual (C# Reference)的相关文章

跟陈湾来完善C++(2), 添加属性功能

上面几篇文章中,我们添加了名称空间优化,添加事件功能.这些对我来说其实已经够了.但还可以加一个属性功能. 当我们在C++中更改一个属性时,平常都是Get函数加上Set函数,但是这样,没有直接写一个成员变量方便.例如: a.SetValue(a.GetValue() + 1); 没有 a.Value = a.Value + 1; 方便. 但是这种方便只有在调用有属性功能的对象时才能使用.在创建属性的时候我还是用老套路,写一个Get和Set函数,该干啥还是干啥.我的属性功能其实就是在类中添加一个共有

Operating System: Three Easy Pieces --- Paging: TLB (Note)

Using paging as the core mechanism to support virtual memeory can lead to high performance overheads. By chopping the address space into small, fixed-sized units (pages), paging requires a large amount of mapping information. Because that mapping inf

Linux -- top (man)

TOP(1)                                                             User Commands                                                             TOP(1) NAME       top - display Linux processes SYNOPSIS       top -hv|-bcHiOSs -d secs -n max -u|U user -p p

C++ Core Guidelines

C++ Core Guidelines September 9, 2015 Editors: Bjarne Stroustrup Herb Sutter This document is a very early draft. It is inkorrekt, incompleat, and pµøoorly formatted. Had it been an open source (code) project, this would have been release 0.6. Copy

Translation Lookaside Buffer

COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION In principle, then, every virtual memory reference can cause two physical mem-ory accesses: one to fetch the appropriate page table entry, and one to fetch the desired dat

C++ 虚函数机制学习

致谢 本文是基于对<Inside the c++ object model>的阅读和gdb的使用而完成的.在此感谢Lippman对cfront中对象模型的解析,这些解析帮助读者拨开迷雾.此外,Linux下无比强大的gdb工具更是驱散"黑暗"的"明灯".  :) No-Inheritance 1 class Base { 2 public: 3 int a = 21; 4 static int b; 5 int c = 22; 6 7 void showB

java.lang.NullPointerException: Attempt to invoke virtual method &#39;java.util.List com.yunweather.app.db.YunWeatherDB.loadProvinces()&#39; on a null object reference

NullPointerException:查看自己的什么地方是否对空指针进行了操作 Attempt to invoke virtual method 'java.util.List com.yunweather.app.db.YunWeatherDB.loadProvinces()' on a null object reference 尝试用一个空对象引用调用LoadProvinces()方法,查看调用LoadProvinces()的对象是否初始化,很可能是因为你没有初始化就调用了LoadPr

Effective C++ 条款九、十 绝不在构造和析构过程中调用virtual函数|令operator=返回一个reference to *this

  1.当在一个子类当中调用构造函数,其父类构造函数肯定先被调用.如果此时父类构造函数中有一个virtual函数,子类当中也有,肯定执行父类当中的virtual函数,而此时子类当中的成员变量并未被初始化,所以无法调用子类与之对应的函数.即为指向虚函数表的指针vptr没被初始化又怎么去调用派生类的virtual函数呢?析构函数也相同,派生类先于基类被析构,又如何去找派生类相应的虚函数? 2.做法:将子类的某个函数改为non-virtual,然后在子类构造函数中传递参数给父类函数.然后父类的构造函数

java.lang.NullPointerException: Attempt to invoke virtual method &#39;void 、Handler.removeMessages(int)&#39; on a null object reference

onDestory进行释放Handler时,需要判断null if(null != mHandler) { mHandler.removeMessages(MSG_CHANGE_TEXT_COLOR); mHandler.removeMessages(MSG_JUMP_TO_SUCCESS_PAGE); mHandler.removeMessages(MSG_PLAY_LITTLE_PEOPLE_ANIMATION); mHandler.removeMessages(MSG_PLAY_WRONG