C# 中 virtual 和 new 关键字的用法
面向对象编程中,通常在基类中定义方法,并在派生类中重写或重新定义这些方法。虽然 "virtual" 和 "new" 关键字都可以用来修改方法声明,但它们有不同的实现方式。
virtual 重写
new 关键字
示例
考虑以下代码:
<code class="language-csharp">public class Base { public virtual bool DoSomething() { return false; } } public class Derived : Base { public override bool DoSomething() { return true; } }</code>
如果我们创建一个 Derived 的实例并将其存储在 Base 类型的变量中,对 DoSomething() 的调用将调用 Derived 中重写的方法:
<code class="language-csharp">Base a = new Derived(); a.DoSomething(); // 返回 true</code>
相反,如果我们在 Derived 中使用 new 关键字,对 DoSomething() 的调用将调用 Derived 中的新方法,即使变量是 Base 类型:
<code class="language-csharp">public class Derived : Base { public new bool DoSomething() { return true; } }</code>
<code class="language-csharp">Base a = new Derived(); a.DoSomething(); // 返回 true (Derived 中的新方法)</code>
何时使用 virtual 重写与 new
以上是虚拟与C#中的新事物:何时覆盖或隐藏基类方法?的详细内容。更多信息请关注PHP中文网其他相关文章!