2016-12-21 29 views
4

我有這樣的方法:不容有兩種方法具有相同簽名但不同的泛型約束

public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func) 
    where TResult : AnotherType 

現在我想這個方法也出現IEnumerable<AnotherType>。所以我寫了這個,這顯然doesn't編譯:

public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func) 
    where TResult : IEnumerable<AnotherType> 

我得到的編譯器錯誤:

Member with the same signature already declared

我讀Member with the same signature already defined with different type constraints與另一返回類型交易會員。然而,在我的例子中我不區分在方法的返回類型,但其PARAM列表這是擺在首位Func<MyType, TResult>,並在第二個Func<IEnumerable<MyType>, TResult>上。但編譯器無法處理這個問題。

有其他的方法相比,第二個例子有另一種方法,叫什麼名字?

+2

通用約束不是方法簽名的一部分,因此不能創建具有不同約束TEO相同的方法。 –

+1

如果你無論如何定義的類型,爲什麼通用所有,而不是在另一個是'Func鍵'在一個和'Func鍵>'? –

+0

@ Dr.Coconut我已經在我的這篇文章中提到過。 – HimBromBeere

回答

5

確實有兩個方法重載不準由通用約束完全不同。

在你的情況我不知道,如果你甚至需要TResult becuause IEnumerable<out T>(如也由阿爾菲古達克評論)是協變的TFunc<in T1, out TResult>TResult協變。

所以嘗試:

public IEnumerable<MyType> DoSomething(Func<MyType, AnotherType> func) 

和:

public IEnumerable<MyType> DoSomething(Func<MyType, IEnumerable<AnotherType>> func) 

由於提到的協方差,會被罰款如何使用通話以上的重載時,比AnotherType更多的派生類。


另一種選擇:

public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, TResult> func) 
    where TResult : AnotherType 

和:

public IEnumerable<MyType> DoSomething<TResult>(Func<MyType, IEnumerable<TResult>> func) 
    where TResult : AnotherType 

在這種替代方法,簽名不同,約束在兩個重載相同。即使AnotherTypeinterfaceTResult是實現接口的struct(值類型),即協方差(out Tout TResult)不起作用的情況下,這可以工作。

+0

哦,親愛的,最簡單的解決方案總是最好的。 – HimBromBeere

相關問題