简体   繁体   中英

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 .

Is this possible if dog and cat would have Animal s as base? 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 :

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? I don't get that logic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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