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 ...
随机推荐
- java虚拟机(八)--java性能监控与故障处理工具
问题定位: 除了个人经验,知识,工具也是很重要的,通过数据进行问题分析,包括:运行日志.异常堆栈.GC日志.线程快照(threaddump/javacore文件 ).堆转储快照(heapdump/hp ...
- 【转载】jxl的使用总结(java操作excel)
jxl.jar是通过java操作excel表格的工具类库: 链接:https://pan.baidu.com/s/1AAT_eA_Q47zFeQohap6eQg 提取码:777b 1:通过模拟实现创建 ...
- Python isalpha() 方法检测字符串是否只由字母组成。
Python isalpha() 方法检测字符串是否只由字母组成.
- lua排序算法
SEED = ; --随机序列 可任取 NUM = ; --排序规模 --随机序列 初始数据 function GenRnd( seed, n ) --生成随机数 data = {}; local r ...
- flask——CSRFToken保护
根据 csrf_token 校验原理,具体操作步骤有以下几步: 1.后端生成 csrf_token 的值,在前端请求登录或者注册界面的时候将值传给前端,传给前端的方式可能有以下两种: 在模板中的 Fr ...
- Windows窗口创建的具体步骤
/*实现窗口创建的六步骤:第一步:创建入口函数WinMain第二步:注册窗口类第三部:实现回调函数的功能第四步:显示窗口第五步:更新窗口第六步:消息循环*/ #include "stdafx ...
- qemu-guest-agent简介
经常使用vmWare的同学都知道有vmware-tools这个工具,这个安装在vm内部的工具,可以实现宿主机与虚拟机的通讯,大大增强了虚拟机的性能与功能, 如vmware现在的Unity mode下可 ...
- RabbitMQ-基本概念(一)
整体架构模型 Producer 消息生产者,生产者创建消息然后发布到RabbitM中,消息一般包含2个部分 消息体(payload)和标签 消息体就是带有业务逻辑结构的数据,消息标签用来表述这条消息, ...
- CF558E A simple task 线段树
这道题好猥琐啊啊啊啊啊啊 写了一个上午啊啊啊啊 没有在update里写pushup啊啊啊啊 题目大意: 给你一个字符串s,有q个操作 l r 1 :把sl..rsl..r按升序排序 l r 0 :把s ...
- zoj——1202 Divide and Count
Divide and Count Time Limit: 2 Seconds Memory Limit: 65536 KB Jack has several beautiful diamon ...