2010-10-23 62 views
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(); 
    } 
} 

回答

1

我不知道你的具體使用情況,但如果你把非泛型方法,而是約束泛型方法來IBASE的例子仍將編譯。

public interface IBase {} 

public interface IChildA : IBase {} 

public interface IChildB : IBase {} 

public static class BaseExtensions 
{ 
    public static T Touch<T>(this T self) where T : IBase { return self; } 
} 

public static class TestClass 
{ 
    public static void Test() 
    { 
     IChildA a = null; 
     IBase firstTry = a.Touch(); 

     IChildB b = null; 
     IChildB touchedB = b.Touch(); 
    } 
}