我写了一个简单的例子来澄清我的问题。这是代码:
internal interface IAnimal
{
string Name { get; set; }
}
class Animal : IAnimal
{
public string Name { get; set; }
}
class Cow : Animal {}
class Sheep : Animal {}
internal interface IFarm<T> where T : IAnimal
{
T TheAnimal { get; }
}
class Farm<T> : IFarm<T> where T : IAnimal
{
public T TheAnimal { get; }
}
class CattleFarm : Farm<Cow> {}
class SheepFarm : Farm<Sheep> {}
class Demo
{
private IFarm<IAnimal> AnyFarm;
void Foo()
{
AnyFarm = new CattleFarm();
var name = AnyFarm.TheAnimal.Name;
AnyFarm = new SheepFarm();
name = AnyFarm.TheAnimal.Name;
}
}
为什么在尝试将CattleFarm或SheepFarm分配给AnyFarm时会出现编译器错误?
我的错在哪里?