2
我有一個基本接口和幾個繼承接口。有基礎接口的擴展方法修改對象並返回基類的新實例(IChildA.Touch() => IBase
,IBase.Touch() => IBase
)。擴展方法和通用約束的問題
對於一個繼承路徑(IChildB
和後代),我想實現擴展方法,返回與調用對象(IGrandChildB.Touch() => IGrandChild
)相同類型的對象。爲此,我想指定一個限制爲IChildB
後代的單一通用擴展方法。
這工作到目前爲止,但現在編譯器無法解析來自IChildA
的呼叫。它嘗試使用IChildB
路徑的擴展方法,並且失敗,而不是使用IBase
接口的擴展方法。有沒有一種優雅的方法來解決這個問題?
public interface IBase {}
public interface IChildA : IBase {}
public interface IChildB : IBase {}
public static class BaseExtensions
{
public static IBase Touch(this IBase self) { return self; }
public static T Touch<T>(this T self) where T : IChildB { return self; }
}
public static class TestClass
{
public static void Test()
{
IChildA a = null;
IBase firstTry = a.Touch(); //Cannot resolve to BaseExtensions.DoSomething(this IBase obj)
IBase secondTry = ((IBase)a).Touch(); //Resolves to BaseExtensions.DoSomething(this IBase obj)
IChildB b = null;
IChildB touchedB = b.Touch();
}
}