C#多态和泛型类型匹配错误

时间:2015-03-26 17:03:59

标签: c# generics

我有一个与此相似的结构

enum AnimalType {dog, cat}

class Animal{}
class Dog : Animal {}
class Cat : Animal {}

class Vet<T> where T : Animal {}
class DogVet : Vet<Dog> {}
class CatVet : Vet<Cat> {}

为什么我不能这样做?

...
Vet<Animal> myVet = new DogVet();
...

为什么我不能像这样向Dictionary添加元素?

...
Dictionary<AnimalType, Vet<Animal>> _vetList = new Dictionary<AnimalType, Vet<Animal>>();
_vetList.Add(AnimalType.dog, new DogVet());
...

应该怎么做?

4 个答案:

答案 0 :(得分:6)

这是一个经典的协方差问题。 Vet<Dog>不是Vet<Animal>。如果你继续这个比喻,Vet<Dog>只能 对待狗。您不能将它用作可以治疗任何种动物的兽医。

假设您有一个Treat函数:

public void Treat<T>(T patient) {}

现在,如果Vet<Dog>Vet<Animal>,那么这将是可能的:

Vet<Animal> dogVet = new Vet<Dog>();
dogVet.Treat(new Cat());  // but I can only treat dogs!!!

答案 1 :(得分:2)

要做到这一点,你需要协变(或逆变)类型参数。遗憾的是,您只能在接口或委托上指定这些,而不能在类上指定。获得所需内容的一种方法是在Vet类之上创建一个接口,如下所示:

    // Not sure what you need this enum for, but OK...
    enum AnimalType {dog, cat}

    class Animal{}
    class Dog : Animal {}
    class Cat : Animal {}

    // Create an interface with covariant parameter
    // i.e. an IVet<T> is also an IVet<Animal> for all T deriving from Animal.
    interface IVet<out T> where T : Animal {}

    // Made Vet abstract. You can still use this to provide base implementations for concrete Vets.
    abstract class Vet<T> : IVet<T> where T : Animal {}

    class DogVet : Vet<Dog> {}
    class CatVet : Vet<Cat> {}

    static void Main()
    {
            // Must use the interface here.
            IVet<Animal> vet = new DogVet();
    }

说实话,你发布的代码让我想知道问题不在于你的代码设计而不是语法。

请注意,虽然这是汇编,但D Stanley的回答中的警告是有效的。例如,您现在无法在界面中添加方法void Treat(T patient)

您发现自己检查运行时类型或获取编译错误的那一刻,因为您的基类定义了一个以T为参数的函数,并且它不会接受{{1}的实现在派生类中,您应该重新设计您的程序。事实上,我现在会认真考虑这个问题。

这里的代码气味是你在Dog上有一个继承树,你正在用另一个继承树Animal来模仿它。未能为新的Vet衍生产品添加适当的Vet衍生产品会让您头疼。

答案 2 :(得分:0)

主要原因是仿制药不支持协方差。以下信息摘自Jon Skeet的书“深入研究”。

简短的回答是因为这是合法的,但如果允许则无效。

Dictionary<AnimalType, Vet<Animal>> _vetList = new Dictionary<AnimalType, Vet<Cat>>();
_vetList.Add(AnimalType.Dog, new Vet<Dog>());

由于字典被告知它使用的是动物,但实际的对象是Cats,它会在运行时失败。再次根据本书,设计人员宁愿编译时失败而不是运行时崩溃,因此在尝试执行此操作时会出错。

答案 3 :(得分:0)

这称为协方差,仅在委托和接口中支持此功能。

例如:

// Covariance
IEnumerable<object> x = new List<string>();

详细了解协方差和逆变in MSDN