如果有一組類實現一個接口。泛型和接口枚舉
interface IMyinterface<T>
{
int foo(T Bar);
}
我想將它們全部推到列表中並通過它們列舉。
List<IMyinterface> list
foreach(IMyinterface in list)
// etc...
但編譯器想知道T是什麼。我可以這樣做嗎?我怎樣才能克服這個問題?
如果有一組類實現一個接口。泛型和接口枚舉
interface IMyinterface<T>
{
int foo(T Bar);
}
我想將它們全部推到列表中並通過它們列舉。
List<IMyinterface> list
foreach(IMyinterface in list)
// etc...
但編譯器想知道T是什麼。我可以這樣做嗎?我怎樣才能克服這個問題?
沒有IMyinterface類型,只有一個IMyinterface`1類型需要類型參數。你可以創建一個IMyInterface的類型: -
interface IMyinterface { ... }
然後從它繼承
interface IMyinterface<T> : IMyinterface { ... }
您需要移動你想在foreach循環使用的IMyInterface的定義的任何成員。
如果你打算在簽名中調用T的方法,答案是你不能。否則,你可以做anthonywjones表明
你仍然需要告訴編譯T是在一定的時間,但你剛纔問什麼可以做:
interface IMyinterface
{
int foo<T>(T Bar);
}
List<IMyinterface> list = new List<IMyinterface>();
foreach(IMyinterface a in list){}