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. 题解 洛谷P4035/BZOJ1013【[JSOI2008]球形空间产生器】

    题目链接在这QvQ "你要求出这个n维球体的球心坐标",这使我想到的解方程...... 先假设n=2,这是一个二维平面.设圆心的坐标为\((x,y)\),有两个坐标\((a_1,b ...

  2. Luogu P1315 观光公交

    # 解题思路 一开始自己想了一个贪心,虽然贪心的主要思路是对的,但并不会统计游客用的旅行时间.所以就去题解里面看看,第一篇是最小费用最大流,会比较麻烦,所以就去看了看底下的贪心,第一篇贪心被卡掉了,看 ...

  3. VIM命令大全(图+文)

    在命令状态下对当前行用== (连按=两次), 或对多行用n==(n是自然数)表示自动缩进从当前行起的下面n行.你可以试试把代码缩进任意打乱再用n==排版,相当于一般IDE里的code format.使 ...

  4. mysql 替换数据库字段内容

    去掉数据库字段单引号 update company_info set company=REPLACE(company,"'","");

  5. LINUX:Contos7.0 / 7.2 LAMP+R 下载安装Apache篇

    文章来源:http://www.cnblogs.com/hello-tl/p/7568803.html 更新时间:2017-09-21 15:38 简介 LAMP+R指Linux+Apache+Mys ...

  6. Spider-scrapy断点续爬

    scrapy的每一个爬虫,暂停时可以记录暂停状态以及爬取了哪些url,重启时可以从暂停状态开始爬取过的URL不在爬取 实现暂停与重启记录状态 方法一: 1.首先cd进入到scrapy项目里(当然你也可 ...

  7. S3C2440的内存情况在NAND FLASH或者NOR FLASH启动的情况下

    1,从NANDFLASH启动时,在ARM上电时,ARM会自动把NANDFLASH前4K的内容拷贝到S3C2440内部SRAM中,同时把SRAM的地址映射到0X00000000.ARM上电后会从SRAM ...

  8. source insight中的快捷键总结

    1.快捷键 1,Shift+F8高亮显示指定字符. 2,Ctrl+F找出来的结果用F4,F3前进后退查找. 3,Alt+,后退alt+.前进查找关键字. 4,Alt+G或者F5跳转到某个固定的行号. ...

  9. 关于自定义checkbox-radio标签的样式的方法(label 和 background-position理解)

    label label标签有一个很好的作用就是扩大表单控件元素的点击区域. 一般有两种方法可以达到效果:(1)使用label标签包裹表单控件(2)设置label标签的for属性和表单的id属性一致 这 ...

  10. 【存储过程】MySQL存储过程/存储过程与自定义函数的区别

    ---------------------------存储过程-------------------- 语法: 创建存储过程: CREATE [definer = {user|current_user ...