我寫了這個擴展方法(編譯):平展IEnumerable <IEnumerable <>>;瞭解泛型
public static IEnumerable<J> Flatten<T, J>(this IEnumerable<T> @this)
where T : IEnumerable<J>
{
foreach (T t in @this)
foreach (J j in t)
yield return j;
}
下面的代碼將導致編譯時錯誤(沒有合適的方法找到),爲什麼呢?:
IEnumerable<IEnumerable<int>> foo = new int[2][];
var bar = foo.Flatten();
如果我實現擴展類似下面,我沒有得到任何編譯時錯誤:
public static IEnumerable<J> Flatten<J>(this IEnumerable<IEnumerable<J>> @this)
{
foreach (IEnumerable<J> js in @this)
foreach (J j in js)
yield return j;
}
編輯(2):這個問題我考慮的回答,但它提出了關於另外一個問題重載解析和類型約束。我把這個問題放在這裏:Why aren't type constraints part of the method signature?
您的編輯不起作用,因爲您有太多的周圍的enumerable。 'foo.Flatten,int>();'應該工作。 –
dlev
2012-02-25 02:20:53