我想学习如何用c#创建泛型类。有人可以解释为什么我运行这个程序时出现编译错误。C#泛型与接口
我创建了IZooAnimal接口。所有的动物园动物都会实现这个界面。
public interface IZooAnimal
{
string Id { get; set; }
}
public class Lion : IZooAnimal
{
string Id { get; set; }
}
public class Zebra : IZooAnimal
{
public string Id { get; set; }
}
的ZooCage将持有同一类型
public class ZooCage<T> where T : IZooAnimal
{
public IList<T> Animals { get; set; }
}
动物园类的动物有笼子
public class Zoo
{
public IList<ZooCage<IZooAnimal>> ZooCages { get; set; }
}
使用类节目
class Program
{
static void Main(string[] args)
{
var lion = new Lion();
var lionCage = new ZooCage<Lion>();
lionCage.Animals = new List<Lion>();
lionCage.Animals.Add(lion);
var zebra = new Zebra();
var zebraCage = new ZooCage<Zebra>();
zebraCage.Animals = new List<Zebra>();
zebraCage.Animals.Add(zebra);
var zoo = new Zoo();
zoo.ZooCages = new List<ZooCage<IZooAnimal>>();
zoo.ZooCages.Add(lionCage);
}
}
当我编译我得到以下结果翼错误: 错误2参数1:无法从“ConsoleApplication2.ZooCage<ConsoleApplication2.Lion>
”转换为“ConsoleApplication2.ZooCage<ConsoleApplication2.IZooAnimal>
”
我有什么变化,以使我的程序运行呢?
阅读关于协方差和反变量......也许开始[这里](http://stackoverflow.com/q/2033912/644812)? –