c# – 通用方法处理IEnumerable不同于泛型类型

前端之家收集整理的这篇文章主要介绍了c# – 通用方法处理IEnumerable不同于泛型类型前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
请检查以下代码段:
  1. public interface ICountable { }
  2. public class Counter<T>
  3. where T : ICountable
  4. {
  5. public int Count(IEnumerable<T> items)
  6. {
  7. return 0;
  8. }
  9.  
  10. public int Count(T Item)
  11. {
  12. return 0;
  13. }
  14. }
  15.  
  16. public class Counter
  17. {
  18. public int Count<T>(IEnumerable<T> items)
  19. where T : ICountable
  20. {
  21. return 0;
  22. }
  23.  
  24. public int Count<T>(T Item)
  25. where T : ICountable
  26. {
  27. return 0;
  28. }
  29. }

计数器的两个版本仅在通用参数的规范中有所不同.其中一个定义为通用类型参数,另一个定义为通用参数.两者都限制方法参数来实现ICountable接口.我会分别将它们称为具体的和非具体的.

现在,我正在定义一个实现ICountable接口的类和一个实例集合:

  1. public class CItem : ICountable { }
  2. var countables = new List<CItem>();

然后,我想在集合中使用两个Counter类.

  1. var specific = new Counter<CItem>();
  2. var nonspecific = new Counter();
  3.  
  4. specific.Count(countables);
  5. 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>‘ to ICountable.

似乎非特定版本使用错误的签名作为集合.

为什么他们的行为不一样?
如何指定非特定版本以与其他版本相同?

注意:我知道这个例子是不现实的.然而,我在一个非常复杂的扩展方法的场景中面临这个问题.为了简单起见,我使用这些类

提前致谢

解决方法

非特定类的问题是编译器在编译时不知道类型T,所以为什么它不能为方法Count< T>()选择正确的重载.但是,如果设置通用类型约束,编译器现在知道要预期的类型…

如果您将使用签名public int Count T(T Item)来注释您的方法,则它将编译,因为它将使用具有正确签名的方法(其为public int Count< T>(IEnumerable< T> items))

如果您通过将列表转换为IEnumerable< CItem>来帮助编译器推断类型,那么它也将被编译并运行明确地:

  1. nonspecific.Count(countables as IEnumerable<CItem>);

看一下简化的场景:

  1. static string A<T>(IEnumerable<T> collection)
  2. {
  3. return "method for ienumerable";
  4. }
  5.  
  6. static string A<T>(T item)
  7. {
  8. return "method for single element";
  9. }
  10.  
  11. static void Main(string[] args)
  12. {
  13. List<int> numbers = new List<int>() { 5,3,7 };
  14. Console.WriteLine(A(numbers));
  15. }

输出:“单元素方法

猜你在找的C#相关文章