请检查以下代码段:
- public interface ICountable { }
- public class Counter<T>
- where T : ICountable
- {
- public int Count(IEnumerable<T> items)
- {
- return 0;
- }
- public int Count(T Item)
- {
- return 0;
- }
- }
- public class Counter
- {
- public int Count<T>(IEnumerable<T> items)
- where T : ICountable
- {
- return 0;
- }
- public int Count<T>(T Item)
- where T : ICountable
- {
- return 0;
- }
- }
计数器的两个版本仅在通用参数的规范中有所不同.其中一个定义为通用类型参数,另一个定义为通用参数.两者都限制方法参数来实现ICountable接口.我会分别将它们称为具体的和非具体的.
现在,我正在定义一个实现ICountable接口的类和一个实例集合:
- public class CItem : ICountable { }
- var countables = new List<CItem>();
然后,我想在集合中使用两个Counter类.
- var specific = new Counter<CItem>();
- var nonspecific = new Counter();
- specific.Count(countables);
- nonspecific.Count(countables);
具体的计数器识别可数列收集应该属于签名int Count(IEnumerable),但不具体的版本不存在.我得到错误:
The type ‘
System.Collections.Generic.List<CItem>
‘ cannot be used as
type parameter ‘T
‘ in the generic type or method
‘Counter.Count<T>(T)
‘. There is no implicit reference conversion from
List<CItem>
‘ toICountable
.
似乎非特定版本使用错误的签名作为集合.
为什么他们的行为不一样?
如何指定非特定版本以与其他版本相同?
注意:我知道这个例子是不现实的.然而,我在一个非常复杂的扩展方法的场景中面临这个问题.为了简单起见,我使用这些类
提前致谢
解决方法
非特定类的问题是编译器在编译时不知道类型T,所以为什么它不能为方法Count< T>()选择正确的重载.但是,如果设置通用类型约束,编译器现在知道要预期的类型…
如果您将使用签名public int Count T(T Item)来注释您的方法,则它将编译,因为它将使用具有正确签名的方法(其为public int Count< T>(IEnumerable< T> items))
如果您通过将列表转换为IEnumerable< CItem>来帮助编译器推断类型,那么它也将被编译并运行明确地:
- nonspecific.Count(countables as IEnumerable<CItem>);
看一下简化的场景:
- static string A<T>(IEnumerable<T> collection)
- {
- return "method for ienumerable";
- }
- static string A<T>(T item)
- {
- return "method for single element";
- }
- static void Main(string[] args)
- {
- List<int> numbers = new List<int>() { 5,3,7 };
- Console.WriteLine(A(numbers));
- }