简体   繁体   English

派生类中具有不同返回类型的抽象类方法

[英]Abstract class method with different return type in derived class

I have this abstract class: 我有这个抽象类:

 abstract class Animal {

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

 }

I want to change the return type to make this: 我想更改返回类型以使其:

     Animal animal;

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

I want to return CatModelList and a DogModelList . 我想返回CatModelListDogModelList

Is this possible if dog and cat would have Animal s as base? 如果狗和猫都将Animal作为基础,这可能吗? And if not what I think is the answer, what would be the correct way of doing this? 如果不是我认为的答案,那么这样做的正确方法是什么?

Then you need generics to supply the type: 然后,您需要泛型来提供类型:

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.
{ }

Where T could be Dog , Cat or any other type deriving from Animal : 其中T可以是DogCat或任何其他源自Animal类型:

class Dog : Animal<Dog>
{ }

Then you can use it using the derived class: 然后可以使用派生类使用它:

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

It seems weird though. 虽然看起来很奇怪。 In an instance of Animal you get the animals? Animal的实例中,您得到了动物吗? I don't get that logic. 我没有那种逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM