8

如果我有这样的方法:

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);
4

1 回答 1

5

通用方法类型推断故意不约束中进行任何推论。相反,从参数形式参数中进行推导,然后根据约束检查推导的类型参数。

有关约束和方法签名的一些设计问题的详细讨论,包括几十个人告诉我认为现有设计是明智的我是错误的,请参阅我关于该主题的文章:

http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

这是Eric Lippert 对类似问题的回答的精确副本。
我决定复制它,因为这个问题更简洁明了。

于 2013-02-22T07:36:32.467 回答