我正在尝试学习如何使用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; }
}
动物园笼子将容纳相同类型的动物。
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);
}
}
当我编译时,出现以下错误:
Error 2 Argument 1: cannot convert from 'ConsoleApplication2.ZooCage<ConsoleApplication2.Lion>
' to 'ConsoleApplication2.ZooCage<ConsoleApplication2.IZooAnimal>
'
我需要做哪些更改才能使程序运行?