本文介绍了C#重载泛型:错误或功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我们有一个简单的例子: void Foo< T>(IEnumerable&项目) { // ... } void Foo< C,T>(C collection,T item)其中C: ICollection< T> { // ... } void Main() { Foo((IEnumerable< int>)new [ ] {1},2); } 编译器说: 类型'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.aspxPlease also read the approximately one million comments telling me that I am wrong for some interesting additional commentary on this issue. 这篇关于C#重载泛型:错误或功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-28 09:38