C# 中 virtual 和 new 关键字的用法
面向对象编程中,通常在基类中定义方法,并在派生类中重写或重新定义这些方法。虽然 "virtual" 和 "new" 关键字都可以用来修改方法声明,但它们有不同的实现方式。
virtual 重写
new 关键字
示例
考虑以下代码:
public class Base
{
public virtual bool DoSomething() { return false; }
}
public class Derived : Base
{
public override bool DoSomething() { return true; }
}
如果我们创建一个 Derived 的实例并将其存储在 Base 类型的变量中,对 DoSomething() 的调用将调用 Derived 中重写的方法:
Base a = new Derived();
a.DoSomething(); // 返回 true
相反,如果我们在 Derived 中使用 new 关键字,对 DoSomething() 的调用将调用 Derived 中的新方法,即使变量是 Base 类型:
public class Derived : Base
{
public new bool DoSomething() { return true; }
}
Base a = new Derived();
a.DoSomething(); // 返回 true (Derived 中的新方法)
何时使用 virtual 重写与 new
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3