【问题标题】:generics and interfaces enumeration泛型和接口枚举
【发布时间】:2008-11-22 12:20:42
【问题描述】:
如果有一组类都实现了一个接口。
interface IMyinterface<T>
{
int foo(T Bar);
}
我想将它们全部放入一个列表中并枚举它们。
List<IMyinterface> list
foreach(IMyinterface in list)
// etc...
但是编译器想知道 T 是什么。我可以这样做吗?我该如何克服这个问题?
【问题讨论】:
标签:
c#
.net
generics
interface
ienumerable
【解决方案1】:
没有 IMyinterface 类型,只有 IMyinterface`1 类型需要类型参数。你可以创建一个 IMyinterface 类型:-
interface IMyinterface { ... }
然后继承它
interface IMyinterface<T> : IMyinterface { ... }
您需要将要在 foreach 循环中使用的任何成员移动到 IMyinterface 定义中。
【解决方案2】:
如果您打算调用签名中带有 T 的方法,答案是您不能。否则,您可以按照 anthonywjones 的建议进行操作
【解决方案3】:
你仍然需要在某个时候告诉编译器 T 是什么,但你所要求的就可以完成:
interface IMyinterface
{
int foo<T>(T Bar);
}
List<IMyinterface> list = new List<IMyinterface>();
foreach(IMyinterface a in list){}