C#泛型超载:错误或意见? [英] C# overloading with generics: bug or feature?
问题描述
让我们下面的简单示例:
Let's have a following simplified example:
void Foo<T>(IEnumerable<T> collection, params T[] items)
{
// ...
}
void Foo<C, T>(C collection, T item)
where C : ICollection<T>
{
// ...
}
void Main()
{
Foo((IEnumerable<int>)new[] { 1 }, 2);
}
编译器说:
Compiler says:
类型System.Collections.Generic.IEnumerable'不能用作在通用类型或方法UserQuery.Foo(C,T)类型参数C。有一个从System.Collections.Generic.IEnumerable'到'了System.Collections.Generic.ICollection'没有隐式引用转换。
The type 'System.Collections.Generic.IEnumerable' cannot be used as type parameter 'C' in the generic type or method 'UserQuery.Foo(C, T)'. There is no implicit reference conversion from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.ICollection'.
如果我改变主
来:
void Main()
{
Foo<int>((IEnumerable<int>)new[] { 1 }, 2);
}
它将工作正常。为什么编译器不选择的右键的过载?
推荐答案
你的问题在这里得到解答。
Your question is answered here.
的 http://blogs.msdn.com/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx
也请阅读大约一万条评论告诉我,我错了,在这个问题上的一些有趣的附加注释。
Please also read the approximately one million comments telling me that I am wrong for some interesting additional commentary on this issue.
这篇关于C#泛型超载:错误或意见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!