关于泛型类的问题

MYsce 2017-05-09 09:09:31
有一个基类Animal使用泛型接口IMethaneProducer<Animal> 派生一Cow类,superCow类继承Cow类
为什么IMethaneProducer<Cow> cowMethaneProducer = supercow;会报错无法转换类型
为什么这个就可以 IMethaneProducer<Animal> animalMethaneProducer =supercow;
public class Animal:IMethaneProducer<Animal> {}

public class Cow:Animal{}

public class superCow:Cow{}

Cow myCow = new Cow("Geronimo");
SuperCow supercow = new SuperCow("Phil");
IMethaneProducer<Cow> cowMethaneProducer = supercow;
IMethaneProducer<Animal> animalMethaneProducer =supercow;

public interface IMethaneProducer< T> {}
...全文
81 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
正怒月神 2017-05-10
  • 打赏
  • 举报
回复
这是一个 协变和逆变的问题 public interface IMethaneProducer< T> {} 改成 public interface IMethaneProducer<in T> { }
xuggzu 2017-05-10
  • 打赏
  • 举报
回复
很简单,因为你实现的泛型接口的T用的是animal而不是cow

110,499

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧