Difference between new and override(新建和覆盖之间的区别)
问题描述
想知道以下之间有什么区别:
Wondering what the difference is between the following:
案例 1:基类
public void DoIt();
案例一:继承类
public new void DoIt();
案例 2:基类
public virtual void DoIt();
案例2:继承类
public override void DoIt();
根据我运行的测试,案例 1 和 2 似乎具有相同的效果.有区别,还是首选方式?
Both case 1 and 2 appear to have the same effect based on the tests I have run. Is there a difference, or a preferred way?
推荐答案
覆盖修饰符可用于虚拟方法,必须用于抽象方法.这表明对于编译器使用最后定义的一种方法的实现.即使该方法在引用上调用它将使用的基类实现覆盖它.
The override modifier may be used on virtual methods and must be used on abstract methods. This indicates for the compiler to use the last defined implementation of a method. Even if the method is called on a reference to the base class it will use the implementation overriding it.
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public override void DoIt()
{
}
}
Base b = new Derived();
b.DoIt(); // Calls Derived.DoIt
如果覆盖 Base.DoIt,将调用 Derived.DoIt.
will call Derived.DoIt if that overrides Base.DoIt.
新的修饰符指示编译器使用您的子类实现而不是父类执行.任何不是的代码引用你的班级但父母类将使用父类实施.
The new modifier instructs the compiler to use your child class implementation instead of the parent class implementation. Any code that is not referencing your class but the parent class will use the parent class implementation.
public class Base
{
public virtual void DoIt()
{
}
}
public class Derived : Base
{
public new void DoIt()
{
}
}
Base b = new Derived();
Derived d = new Derived();
b.DoIt(); // Calls Base.DoIt
d.DoIt(); // Calls Derived.DoIt
将首先调用 Base.DoIt,然后是 Derived.DoIt.它们实际上是两个完全独立的方法,它们恰好具有相同的名称,而不是覆盖基方法的派生方法.
Will first call Base.DoIt, then Derived.DoIt. They're effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.
来源:微软博客
这篇关于新建和覆盖之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:新建和覆盖之间的区别
基础教程推荐
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
