簡體   English   中英

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

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

我有這個抽象類:

 abstract class Animal {

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

 }

我想更改返回類型以使其:

     Animal animal;

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

我想返回CatModelListDogModelList

如果狗和貓都將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>
{ }

然后可以使用派生類使用它:

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

雖然看起來很奇怪。 Animal的實例中,您得到了動物嗎? 我沒有那種邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM