Versioning with the Override and New Keywords (C# Programming Guide)
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 override, virtual, 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
C# Programming Guide
Classes and Structs (C# Programming Guide)
Methods (C# Programming Guide)
Inheritance (C# Programming Guide)
Versioning with the Override and New Keywords (C# Programming Guide)的更多相关文章
- 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 ...
- override (C# Reference)
https://msdn.microsoft.com/en-us/library/ebca9ah3.aspx The override modifier is required to extend o ...
- virtual (C# Reference)
https://msdn.microsoft.com/en-us/library/9fkccyh4.aspx The virtual keyword is used to modify a metho ...
- Polymorphism (C# Programming Guide)
https://msdn.microsoft.com/en-us/library/ms173152.aspx Polymorphism is often referred to as the thir ...
- .NET 面试题: C# override && overloading (C# 覆写 && 重载)
1 1 1 .NET 面试题, C# ,override , overloading, 覆写, 重载,.NET,ASP.NET, override (覆写/重写): 方法名相同,参数的个数和类型相同, ...
- iOS-数据持久化-CoreData
CoreData详解 介绍: 在Cocoa环境下,如果你想使用数据库(如sqlite),你可以使用sql语句的方式通过相关的工具类进行数据库的直接操作.当然你也可以通过别人封装之后的一些简单框架,使得 ...
- 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 ...
- Note_Master-Detail Application(iOS template)_02_YJYAppDelegate.m
//YJYAppDelegate.m #import "YJYAppDelegate.h" #import "YJYMasterViewController.h" ...
- How to Write Doc Comments for the Javadoc Tool
http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html This document describe ...
随机推荐
- Linux下查看CPU信息、机器型号等硬件信息命令
Linux下查看CPU信息.机器型号等硬件信息命令 编写一个bash脚本: vim info.sh #!/bin/bash cat /etc/issue echo "____________ ...
- 剑指offer---以O(1)时间删除链表节点
问题:删除链表节点 要求:以O(1)时间 对于删除指定索引的链表元素大家都很熟悉,思路一般是从头遍历链表直到指定索引位置删除元素,然后维护一下指针即可,时间复杂度O(n).代码如下: // 删除pos ...
- 配置servlet出现java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
拷贝一份sqljdbc.jar放到/WEB-INF/lib即可
- 洛谷 1071 潜伏者(NOIp2009提高组)
[题意概述] 给出三行字符串,前两行代表密码与明文的对应关系,第三行为待翻译的文本.要求按照对应关系翻译文本. [题解] 直接模拟即可. 注意判断Failed的情况. #include<cstd ...
- 18年多校-1002 Balanced Sequence
>>点击进入原题测试<< 思路:自己写没写出来,想不通该怎么排序好,看了杜神代码后补题A掉的.重新理解了一下优先队列中重载小于号的含义,这里记录一下这种排序方式. #inclu ...
- jmeter 性能测试
1. Ramp-up Period(in seconds)代表多长时间内启动所有线程 2. Aggregate Report Samples:总共发给服务器的请求数量 Average:单个请求的平均响 ...
- [luoguP3052] [USACO12MAR]摩天大楼里的奶牛Cows in a Skyscraper(DP)
传送门 输出被阉割了. 只输出最少分的组数即可. f 数组为结构体 f[S].cnt 表示集合 S 最少的分组数 f[S].v 表示集合 S 最少分组数下当前组所用的最少容量 f[S] = min(f ...
- D - Guess UVALive - 4255 拓扑排序
Given a sequence of integers, a1, a2, . . . , an, we define its sign matrix S such that, for 1 ≤ i ≤ ...
- [bzoj1577][Usaco2009 Feb]庙会捷运Fair Shuttle_贪心_线段树
庙会捷运 Fair Shuttle bzoj-1577 Usaco-2009 Feb 题目大意:有一辆公交车从1走到n.有m群奶牛从$S_i$到$E_i$,第i群奶牛有$W_i$只.车有一个容量c.问 ...
- 洛谷——P1396 营救
P1396 营救 题目描述 “咚咚咚……”“查水表!”原来是查水表来了,现在哪里找这么热心上门的查表员啊!小明感动的热泪盈眶,开起了门…… 妈妈下班回家,街坊邻居说小明被一群陌生人强行押上了警车!妈妈 ...