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>
/// 圆
/// </summary>
public class Circle : Shape
{
public Circle(double r) : base(r, )
{
} public override double Area()
{
return PI * x * x;
}
} /// <summary>
/// 球体
/// </summary>
class Sphere : Shape
{
public Sphere(double r) : base(r, )
{
} public override double Area()
{
return * PI * x * x;
}
} /// <summary>
/// 圆柱体
/// </summary>
class Cylinder : Shape
{
public Cylinder(double r, double h) : base(r, h)
{
} public override double Area()
{
return * PI * x * x + * 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());
}
}

virtual (C# Reference)的更多相关文章

  1. abstract (C# Reference)

    https://msdn.microsoft.com/en-us/library/sf985hc5.aspx The abstract modifier indicates that the thin ...

  2. DIY FSK RFID Reader

    This page describes the construction of an RFID reader using only an Arduino (Nano 3.0 was tested, b ...

  3. RFID 读写器 Reader Writer Cloner

    RFID读写器的工作原理 RFID的数据采集以读写器为主导,RFID读写器是一种通过无线通信,实现对标签识别和内存数据的读出和写入操作的装置. 读写器又称为阅读器或读头(Reader).查询器(Int ...

  4. Translation Lookaside Buffer

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION In principle, then, e ...

  5. RFID Reader 线路图收集

    This 125 kHz RFID reader http://www.serasidis.gr/circuits/RFID_reader/125kHz_RFID_reader.htm http:// ...

  6. C++ 虚函数机制学习

    致谢 本文是基于对<Inside the c++ object model>的阅读和gdb的使用而完成的.在此感谢Lippman对cfront中对象模型的解析,这些解析帮助读者拨开迷雾.此 ...

  7. (4)top详解 (每周一个linux命令系列)

    (4)top详解 (每周一个linux命令系列) linux命令 top详解 引言:今天的命令是用来看cpu信息的top top 我们先看man top top - display Linux pro ...

  8. C++ Core Guidelines

    C++ Core Guidelines September 9, 2015 Editors: Bjarne Stroustrup Herb Sutter This document is a very ...

  9. Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayShowHomeEnabled(boolean)' on a null object reference

    /********************************************************************************* * Caused by: java ...

随机推荐

  1. JZOJ5776. 【NOIP2008模拟】小x游世界树

    题目:[NOIP2008模拟]小x游世界树: 题目的附加题解给的很清楚,这里只给一个代码: #include<iostream> #include<cstdio> #inclu ...

  2. MySQL与MyBatis中的查询记录

    1.时间段查询 MySQL:select * from table where ctime >= CURDATE() and ctime <DATE_SUB(CURDATE(),INTER ...

  3. [Python3网络爬虫开发实战] 6.1-什么是Ajax

    Ajax,全称为Asynchronous JavaScript and XML,即异步的JavaScript和XML.它不是一门编程语言,而是利用JavaScript在保证页面不被刷新.页面链接不改变 ...

  4. docker push

    一.确保docker hub上有账号 二.确认要提交的镜像的命名空间为自己账号名称 三.在本地登录docker: docker login 四.提交镜像: docker push zhengchuzh ...

  5. navicat连接mysql8报错,错误提示为1251,原因及解决步骤

    一.错误原因: MySQL8.0版本的加密方式和MySQL5.0的不一样,连接会报错. 二.解决步骤: 1.在linux虚拟机上登录mysql 2.更改加密方式: ALTER USER 'root'@ ...

  6. 树莓派 -- oled 续(2) python

    上文中的代码通过wiringPi的API调用devfs API来显示图片. 这里分析的Python代码也通过类似的方法来显示图片. 主要用到了两个Library. import spidev impo ...

  7. leds-gpio driver 续1

    在上文中分析了gpio-led platform_device是如何定义并注册的. 那么gpio-led platform_device 和 gpio-led platform_driver是如何匹配 ...

  8. RNNCell使用

    目录 Recap input dim, hidden dim SimpleRNNCell Single layer RNN Cell Multi-Layers RNN RNN Layer Recap ...

  9. C语言的移位操作符及位运算

    C语言的移位操作符 位移位运算符是将数据看成二进制数,对其进行向左或向右移动若干位的运算.位移位运算符分为左移和右移两种,均为双目运算符.第一运算对象是移位对象,第二个运算对象是所移的二进制位数. 位 ...

  10. 添物不花钱学JavaEE(基础篇) --HTML

    HTML是什么? HTML – Hyper Text Markup Language HTML官方网址 http://www.w3.org/TR/2014/REC-html5-20141028/ 其实 ...