[英]Why do a child class need to implement a parents interface to hide one of that parents methods in C#?
我在使用第三方庫時發現了這種行為,我需要隱藏並更改其中一種方法。
我有以下設置:
interface IBaseInterface
{
string MethodToHide();
}
class BaseClass : IBaseInterface
{
public string MethodToHide()
{
return "BaseClass";
}
}
class ChildClass : BaseClass
{
new public string MethodToHide()
{
return "ChildClass";
}
}
為什么當我運行以下內容時:
var i = (IBaseInterface) (new ChildClass());
Console.WriteLine(i.MethodToHide());
輸出是
BaseClass的
,但在將ChildClass簽名更改為時
class ChildClass : BaseClass, IBaseInterface
,輸出是
ChildClass
為什么我需要顯式指定ChildClass隱藏的BaseClass方法的接口?
您需要更多地了解覆蓋和隱藏之間的區別:
鏈接: 覆蓋與隱藏
簡而言之:
隱藏 (使用new)根據變量的類型運行方法。
覆蓋會覆蓋該方法,並且只會使用子方法。
編輯 :
使用Interface變量時:
var i = (IBaseInterface) (new ChildClass());
編譯器將搜索接口使用的方法的最佳匹配。
因為您聲明了BaseClass來實現接口,所以將選擇其方法。
如果ChildClass沒有顯式實現接口,則編譯器無法將方法鏈接到接口。 從它的角度來看, BaseClass恰好具有相同名稱的方法。
當您明確聲明ChildClass也實現了接口時,它的方法將是最佳選擇。
您需要在BaseClass中將MethodToHide標記為虛擬。 然后你的ChildClass可以覆蓋它。 有關詳細信息,請參閱http://msdn.microsoft.com/en-us/library/9fkccyh4(v=vs.80).aspx 。
我相信這是規范的相關部分:
10.6.3虛方法在虛方法調用中,進行該調用的實例的運行時類型決定了要調用的實際方法實現。 在非虛方法調用中,實例的編譯時類型是決定因素。
因此,當您將原始對象轉換為IBaseInterface時。 它確定類型是BaseClass,因為它是實現它並調用其方法的類型。 在第二個示例中,它將其解析為ChildClass並調用其方法。
因為main-class實現了接口。 子類只定義了一個與接口無關的新方法。 實際上,子類隱藏了這個方法 - 這就是'new'的作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.