![](/img/trans.png)
[英]Is there another way to change the return type of a static method of an abstract class based on the derived class type in C#?
[英]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();
}
我想返回CatModelList
和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
可以是Dog
, Cat
或任何其他源自Animal
類型:
class Dog : Animal<Dog>
{ }
然后可以使用派生類使用它:
Dog d = new Dog();
animal = d;
dogList = d.GetAnimals();
雖然看起來很奇怪。 在Animal
的實例中,您得到了動物嗎? 我沒有那種邏輯。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.