[英]C# pass generic type as a generic type parameter?
public static C RotateLeft<C, T>(C list, int count) where C : IEnumerable<T>
{
return list.Skip (count).Concat(list.Take(count));
}
我想達到這樣的目標,其中T是IEnumerable的參數類型,而C實現IEnumerable。 這是我想出的語法,但沒有通過編譯器。 有什么辦法得到我想要的嗎? 謝謝!
您為什么不完全省略C
參數?
public static IEnumerable<T> RotateLeft<T>(IEnumerable<T> list, int count)
{
return list.Skip (count).Concat(list.Take(count));
}
編輯:正如Suresh Kumar Veluswamy已經提到的,您也可以將結果簡單地轉換為C
的實例:
public static C RotateLeft<C, T>(C list, int count) where C : IEnumerable<T>
{
return (C) list.Skip(count).Concat(list.Take(count));
}
但是,盡管這將解決您的編譯器問題,但是當嘗試將Concat
的結果InvalidCastException
為C
實例時,它返回InvalidCastException
,因此它不會讓您得到想要的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.