为什么可以';t编译器解析这些泛型类型
本文关键字:泛型类型 编译器 为什么 | 更新日期: 2023-09-27 18:00:26
如果我有这样的方法:
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);
泛型方法类型推理故意不从约束中进行任何推导。相反,从实参和形式参数中进行推导,然后根据约束检查推导的类型实参。
有关约束和方法签名的一些设计问题的详细讨论,包括几十个人告诉我,我认为现有设计是合理的是错误的,请参阅我关于这个主题的文章:
http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx
这是埃里克·利珀特对类似问题的准确回答
我决定抄一下,因为这个问题更简洁明了