为什么编译器无法解析这些泛型类型

Cor*_*ius 8 c# generics

如果我有这样的方法:

public void Foo<T1, T2>(T1 list)
    where T1 : IList<T2>
    where T2 : class
{
    // Do stuff
}
Run Code Online (Sandbox Code Playgroud)

如果我有:

IList<string> stringList = new List<string>();
List<object> objectList = new List<object>();
IList<IEnumerable> enumerableList = new List<IEnumerable>();
Run Code Online (Sandbox Code Playgroud)

然后编译器无法解析要选择的泛型,这会失败:

Foo(stringList);
Foo(objectList);
Foo(enumerableList);
Run Code Online (Sandbox Code Playgroud)

您必须明确指定要使用的泛型:

Foo<IList<string>, string>(stringList);
Foo<IList<object>, object>(objectList);
Foo<List<object>, object>(objectList);
Foo<IList<IEnumerable>, IEnumerable>(enumerableList);
Run Code Online (Sandbox Code Playgroud)

Dan*_*rth 5

泛型方法的类型推断故意并没有使从限制任何扣减.相反,从参数形式参数中进行推导,然后根据约束检查推导出的类型参数.

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

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

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