【发布时间】:2013-02-22 15:36:32
【问题描述】:
如果我有这样的方法:
public void Foo<T1, T2>(T1 list)
where T1 : IList<T2>
where T2 : class
{
// Do stuff
}
现在如果我有:
IList<string> stringList = new List<string>();
List<object> objectList = new List<object>();
IList<IEnumerable> enumerableList = new List<IEnumerable>();
然后编译器无法解析要选择的泛型并且失败:
Foo(stringList);
Foo(objectList);
Foo(enumerableList);
您必须明确指定要使用的泛型:
Foo<IList<string>, string>(stringList);
Foo<IList<object>, object>(objectList);
Foo<List<object>, object>(objectList);
Foo<IList<IEnumerable>, IEnumerable>(enumerableList);
【问题讨论】:
-
旁白,但你真的需要
T1吗?你不能public void Foo<T>(IList<T> list) where T : class吗? -
检查链接问题中的 Eric 答案以及其中链接的博客文章。
-
@Daniel:不关闭这个问题的一个原因,即使它是重复的,也是它简单而简约的代码示例和问题描述。原来的问题真的很难理解。
-
@lc.:很可能,您的评论是正确的,但在某些情况下,这样的事情是有道理的。一个例子是整个类层次结构的流畅扩展方法,其中扩展方法应该返回具体的子类型而不是公共接口。想象
Foo作为扩展方法返回T1。在这种情况下,以下内容将是有效的:new List<...>().Foo(...).AddRange()。 (注意:AddRange是在List<T>上定义的,而不是在IList<T>上定义的。因此,如果Foo将返回IList<T2>,则该代码将不再有效。