无法转换源类型,存在显式转换

时间:2016-11-15 15:13:44

标签: c# syntax-error

我写了一个简单的例子来澄清我的问题。这是代码:

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时会出现编译器错误?

我的错在哪里?

0 个答案:

没有答案