The C# language is designed so that versioning between base and derived classes in different libraries can evolve发展 and maintain backward compatibility向后兼容.

This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is completely supported by C# and does not lead to unexpected behavior.

It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that hides a similarly named inherited method.

In C#, derived classes can contain methods with the same name as base class methods.

  • The base class method must be defined virtual.

  • If the method in the derived class is not preceded by new or override keywords, the compiler will issue a warning and the method will behave as if the new keyword were present.

  • If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class.

  • If the method in the derived class is preceded with the override keyword, objects of the derived class will call that method instead of the base class method.

  • The base class method can be called from within the derived class using the base keyword.

  • The overridevirtual, and new keywords can also be applied to properties, indexers, and events.

By default, C# methods are not virtual. If a method is declared as virtual, any class inheriting the method can implement its own version.

To make a method virtual, the virtual modifier is used in the method declaration of the base class.

The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword.

If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class.

To demonstrate this in practice, assume for a moment that Company A has created a class named GraphicsClass, which your program uses.

The following is GraphicsClass:

class GraphicsClass
{
public virtual void DrawLine() { }
public virtual void DrawPoint() { }
}

Your company uses this class, and you use it to derive your own class, adding a new method:

class YourDerivedGraphicsClass : GraphicsClass
{
public void DrawRectangle() { }
}

Your application is used without problems, until Company A releases a new version of GraphicsClass, which resembles the following code:

class GraphicsClass
{
public virtual void DrawLine() { }
public virtual void DrawPoint() { }
public virtual void DrawRectangle() { }
}

The new version of GraphicsClass now contains a method named DrawRectangle.

Initially, nothing occurs. The new version is still binary compatible with the old version.

Any software that you have deployed will continue to work, even if the new class is installed on those computer systems.

Any existing calls to the method DrawRectangle will continue to reference your version, in your derived class.

However, as soon as you recompile your application by using the new version of GraphicsClass, you will receive a warning from the compiler, CS0108.

This warning informs you that you have to consider how you want your DrawRectangle method to behave in your application.

If you want your method to override the new base class method, use the override keyword:

class YourDerivedGraphicsClass : GraphicsClass
{
public override void DrawRectangle() { }
}

The override keyword makes sure that any objects derived from YourDerivedGraphicsClass will use the derived class version of DrawRectangle.

Objects derived from YourDerivedGraphicsClass can still access the base class version of DrawRectangle by using the base keyword:

base.DrawRectangle();

If you do not want your method to override the new base class method, the following considerations apply.

To avoid confusion between the two methods, you can rename your method.

This can be time-consuming and error-prone易于出错的, and just not practical in some cases.

However, if your project is relatively small, you can use Visual Studio's Refactoring options to rename the method.

For more information, see Refactoring Classes and Types (Class Designer).

Alternatively, you can prevent the warning by using the keyword new in your derived class definition:

class YourDerivedGraphicsClass : GraphicsClass
{
public new void DrawRectangle() { }
}

Using the new keyword tells the compiler that your definition hides the definition that is contained in the base class. This is the default behavior.

Override and Method Selection

When a method is named on a class,

the C# compiler selects the best method to call if more than one method is compatible with the call,

such as when there are two methods with the same name, and parameters that are compatible with the parameter passed.

The following methods would be compatible:

public class Derived : Base
{
public override void DoWork(int param) { }
public void DoWork(double param) { }
}

When DoWork is called on an instance of Derived, the C# compiler will first try to make the call compatible with the versions of DoWork declared originally on Derived.

Override methods are not considered as declared on a class, they are new implementations of a method declared on a base class.

Only if the C# compiler cannot match the method call to an original method on Derived will it try to match the call to an overridden method with the same name and compatible parameters.

For example:

int val = ;
Derived d = new Derived();
d.DoWork(val); // Calls DoWork(double).

Because the variable val can be converted to a double implicitly, the C# compiler calls DoWork(double) instead of DoWork(int).

There are two ways to avoid this.

First, avoid declaring new methods with the same name as virtual methods.

Second, you can instruct the C# compiler to call the virtual method by making it search the base class method list by casting the instance of Derived to Base.

Because the method is virtual, the implementation of DoWork(int) on Derived will be called.

For example:

((Base)d).DoWork(val);  // Calls DoWork(int) on Derived.

For more examples of new and override, see Knowing When to Use Override and New Keywords (C# Programming Guide).

See Also

Versioning with the Override and New Keywords (C# Programming Guide)的更多相关文章

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

    https://msdn.microsoft.com/en-us/library/ms173153.aspx In C#, a method in a derived class can have t ...

  2. override (C# Reference)

    https://msdn.microsoft.com/en-us/library/ebca9ah3.aspx The override modifier is required to extend o ...

  3. virtual (C# Reference)

    https://msdn.microsoft.com/en-us/library/9fkccyh4.aspx The virtual keyword is used to modify a metho ...

  4. Polymorphism (C# Programming Guide)

    https://msdn.microsoft.com/en-us/library/ms173152.aspx Polymorphism is often referred to as the thir ...

  5. .NET 面试题: C# override && overloading (C# 覆写 && 重载)

    1 1 1 .NET 面试题, C# ,override , overloading, 覆写, 重载,.NET,ASP.NET, override (覆写/重写): 方法名相同,参数的个数和类型相同, ...

  6. iOS-数据持久化-CoreData

    CoreData详解 介绍: 在Cocoa环境下,如果你想使用数据库(如sqlite),你可以使用sql语句的方式通过相关的工具类进行数据库的直接操作.当然你也可以通过别人封装之后的一些简单框架,使得 ...

  7. iPhone:4.7 5.5 4 3.5 对应的各个设备屏幕尺寸对应的像素及App上线信息

    Shared App Information You can access these properties from the App Details page in the App Informat ...

  8. Note_Master-Detail Application(iOS template)_02_YJYAppDelegate.m

    //YJYAppDelegate.m #import "YJYAppDelegate.h" #import "YJYMasterViewController.h" ...

  9. How to Write Doc Comments for the Javadoc Tool

    http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html This document describe ...

随机推荐

  1. 模块挂载、切换,uml模式、流程图模式

    模块挂载.切换,uml模式.流程图模式

  2. C++标准库 vector排序

    前天要做一个对C++ STL的vector容器做一个排序操作,之前一直把vector当做一个容量可自动变化的数组,是的,数组,所以打算按照对数组进行排序的方法:用快速排序或是冒泡排序等算法自己写一个排 ...

  3. 散列--P1047 校门外的树

    题目描述 某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是1米.我们可以把马路看成一个数轴,马路的一端在数轴0的位置,另一端在L的位置:数轴上的每个整数点,即0,1,2,-,L,都种有 ...

  4. 网络模型、IP命令、SS命令介绍

    1. 分层对应关系 OSI七层模型和TCP/IP五层模型都属于TCP/IP协议栈,而TCP/IP协议栈只有两种传输层协议:TCP.UDP,所以对于Telnet.FTP这些协议,建议称之为承载在TCP之 ...

  5. LINUX-YUM 软件包升级器 - (Fedora, RedHat及类似系统)

    yum install package_name 下载并安装一个rpm包 yum localinstall package_name.rpm 将安装一个rpm包,使用你自己的软件仓库为你解决所有依赖关 ...

  6. java 数组排序并去重

    https://www.cnblogs.com/daleyzou/p/9522533.htmlimport java.lang.reflect.Array;import java.util.Array ...

  7. 腾讯云,搭建Git服务器

    下载安装 git 任务时间:5min ~ 10min Git 是一款免费.开源的分布式版本控制系统,用于敏捷高效地处理任何或小或大的项目. 此实验以 CentOS 7.2 x64 的系统为环境,搭建 ...

  8. ansible roles例子

    #理解 changed_when failed_when become become_user ansible_become ansible_become_user static #检查group_v ...

  9. [luoguP3565] [POI2014]HOT-Hotels(dfs)

    传送门 三点在树上距离相等的情况只有一种,就是以某一个点为中心,三个点到这个点的距离相等. 所以直接枚举每个点作为中心,dfs这个中心的子树,根据乘法原理统计答案即可. 时间复杂度 O(n2) (n ...

  10. spoj 375 树链剖分模板

    /* 只是一道树链刨分的入门题,作为模板用. */ #include<stdio.h> #include<string.h> #include<iostream> ...