小编Mar*_*arc的帖子

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

我有一个类似的结构

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> {}
Run Code Online (Sandbox Code Playgroud)

为什么我不能这样做呢?

...
Vet<Animal> myVet = new DogVet();
...
Run Code Online (Sandbox Code Playgroud)

为什么我不能添加这样的元素Dictionary

...
Dictionary<AnimalType, Vet<Animal>> _vetList = new Dictionary<AnimalType, Vet<Animal>>();
_vetList.Add(AnimalType.dog, new DogVet());
...
Run Code Online (Sandbox Code Playgroud)

该怎么做?

c# generics

0
推荐指数
1
解决办法
84
查看次数

标签 统计

c# ×1

generics ×1