C#重载泛型:错误或功能? [英] C# overloading with generics: bug or feature?
问题描述
我们有一个简单的例子:
void Foo< T>(IEnumerable&项目)
{
// ...
}
void Foo< C,T>(C collection,T item)
其中C: ICollection< T>
{
// ...
}
void Main()
{
Foo((IEnumerable< int>)new [ ] {1},2);
}
编译器说:
< blockquote>
类型'System.Collections.Generic.IEnumerable'不能用作通用类型或方法'UserQuery.Foo(C,T)'中的类型参数'C'。没有从System.Collections.Generic.IEnumerable到System.Collections.Generic.ICollection的隐式引用转换。
如果我将 Main
更改为:
b {
Foo< int>((IEnumerable< int>)new [] {1},2);
}
为什么编译器不选择重载
? >
http://blogs.msdn.com/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx
请阅读大约100万条评论,告诉我我对这个问题的一些有趣的额外评论错了。
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:
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'.
If I change Main
to:
void Main()
{
Foo<int>((IEnumerable<int>)new[] { 1 }, 2);
}
It will work ok. Why compiler does not choose the right overload?
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屋!