派生 class 中具有不同 return 类型的抽象 class 方法

Abstract class method with different return type in derived class

我有这个摘要class:

 abstract class Animal {

    public abstract List<??????> getAnimals();

 }

我想更改 return 类型来实现:

     Animal animal;

     if(/*Somthing*/){
          animal = new Cat();
          catList = animal.getAnimals();
     }else{
          animal = new Dog(); 
          dogList = animal.getAnimals();
     }

我要returnCatModelList和一个DogModelList.

如果狗和猫以 Animal 为基础,这可能吗?如果不是我认为的答案,那么正确的做法是什么?

然后你需要泛型来提供类型:

abstract class Animal<T> : Animal where T : Animal
{
    public abstract List<T> GetAnimals();
}

abstract class Animal
// base type to make things easier. Put in all the non-generic properties.
{ }

其中 T 可以是 DogCat 或从 Animal:

派生的任何其他类型
class Dog : Animal<Dog>
{ }

然后你可以使用派生的class:

Dog d = new Dog();
animal = d;
dogList = d.GetAnimals();

虽然看起来很奇怪。在Animal的实例中你得到了动物?我不明白这个逻辑。