[英]Method hiding and the “new” keyword
對於我的生活,盡管有關於它的所有文檔,但我從未理解“方法隱藏”。
覆蓋意味着在派生類中使用實現。 我是否認為隱藏(通過使用“new”關鍵字“)將意味着使用基類定義?在這種情況下,那么為什么要在繼承類中編寫方法?
實際上我的兩個問題是:
你的理解有點過時了。
首先,重寫方法意味着即使將實例轉換為其基類型,也將使用新實現,因為虛方法表中有適當的條目。
隱藏方法時,當實例作為基類型轉換時,將使用基本實現,因為虛方法表中沒有條目。
給定以下類定義:
public class Base
{
public virtual void Say()
{
Console.WriteLine("Hello World!");
}
}
public class A : Base
{
public new void Say()
{
Console.WriteLine("42");
}
}
public class B : Base
{
public override void Say()
{
Console.WriteLine("Goodbye, Cruel World!");
}
}
以下代碼將產生:
var a = new A();
var b = new B();
var aAsBase = a as Base;
var bAsBase = b as Base;
a.Say(); // 42
aAsBase.Say(); // Hello World!
b.Say(); // Goodbye, Cruel World!
bAsBase.Say(); // Goodbye, CruelWorld!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.