[英]create an interface with base classes while derived classes contain their own implementation
[英]How to call the base interface implementation when derived classes re-implement the interface?
因此,出於某種原因,我正在測試C#和.NET VM的限制。 我遇到了一些令人困惑的行為。
拿這些類和接口:
public interface ITest
{
void Test();
void Test2();
}
public abstract class Base : ITest
{
void ITest.Test()
{
Console.WriteLine("base");
}
public void Test2()
{
Console.WriteLine("base2");
}
public void Test3()
{
Console.WriteLine("base3");
}
}
public class Impl : Base, ITest
{
void ITest.Test()
{
Console.WriteLine("impl");
}
void ITest.Test2()
{
Console.WriteLine("impl2");
}
public void Test3()
{
Console.WriteLine("impl3");
}
}
然后像這樣使用它們:
var i = new Impl();
var b = (Base)i;
var itest1 = (ITest)i;
var itest2 = (ITest)b;
itest1.Test();
itest2.Test();
itest1.Test2();
itest2.Test2();
i.Test2();
b.Test2();
i.Test3(); //for reference, a standard non-virtual method outside of an interface
b.Test3();
我期望輸出看起來像這樣:
impl
base
impl2
base2
impl2
base2
impl3
base3
但當然,事情不可能那么簡單。 所以,實際輸出是這樣的:
impl
impl
impl2
impl2
base2
base2
impl3
base3
除了這種瘋狂的奇怪行為之外,是否可以訪問Base.Test()實現?
也許你應該檢查為什么你會發現你得到奇怪的結果。 對我來說,看起來你得到了你所實現的。
沒有辦法獲得Base.Test
因為沒有Base.Test
。 您需要通過接口顯式訪問它,然后它不再是Base
,而是Impl
,因為底層的真實對象不是Base
類型。
Base
明確實現了ITest.Test()
。 這是一個實現,但它是一個“私有”實現,只能通過ITest
接口訪問。
最重要的是, Impl
正在重新實現 ITest.Test()
,因此當您嘗試使用itest2.Test()
您將指向稍后的重新實現 。
這里的兩個關鍵點是:
Base.Test()
。 Impl
上重新實現它,殺死了在Base
上訪問ITest.Test()
實現的所有可能性。 我可以建議稍微重命名一下這個問題: 當派生類顯式重新實現接口時,如何調用基接口顯式實現? 因為那就是你要問的......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.