c# – 为什么列表在协变界面MyInterface上无效

前端之家收集整理的这篇文章主要介绍了c# – 为什么列表在协变界面MyInterface上无效前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
跟进问题到 a previous question,这被确定为共同问题.进一步,如果我修改IFactory如下:
  1. class Program
  2. {
  3. static void Main(string[] args)
  4. {
  5. IFactory<IProduct> factory = new Factory();
  6. }
  7. }
  8.  
  9. class Factory : IFactory<Product>
  10. {
  11. }
  12.  
  13. class Product : IProduct
  14. {
  15. }
  16.  
  17. interface IFactory<out T> where T : IProduct
  18. {
  19. List<T> MakeStuff();
  20. }
  21.  
  22. interface IProduct
  23. {
  24. }

我得到:

Invalid variance: The type parameter T must be invariantly valid on SandBox.IFactory.MakeStuff(). T is covariant.

为什么这不一定有效?如何解决

解决方法

@Craig’s answer是正确的.要解决,请将其更改为:
  1. IEnumerable<T> MakeStuff()

编辑:至于为什么,看看IEnumerable<T> Interface的定义:

  1. public interface IEnumerable<out T> : IEnumerable

请注意,IList<T> Interface没有out关键字.对于接口和委托,而不是类,通用类型参数支持差异,因此它不适用于List< T>.

猜你在找的C#相关文章