【问题标题】:Abstract class method with different return type in derived class派生类中具有不同返回类型的抽象类方法
【发布时间】:2025-11-24 22:50:01
【问题描述】:

我有这个抽象类:

 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

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

【问题讨论】:

    标签: c# abstract return-type base-class


    【解决方案1】:

    那么你需要泛型来提供类型:

    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 的例子中,你得到动物了吗?我不明白这个逻辑。

    【讨论】:

    • 它没有逻辑我只是想保持简单。因为实际上我需要从具有适配器模式的表中加载不同的模型。它是研究的一部分。谢谢你的遮阳篷!
    • 我必须为每个通用类型实例化 Animal 还是只能像我的问题一样在开始时实例化它?
    最近更新 更多