继承后不能返回新的类类型

本文关键字:类型 返回 不能 继承 | 更新日期: 2023-09-27 17:49:24

public class abstract animal
{
     // many fields
     public string Name {get;set;}
     public int id {get; set;}
     // method, return self
     public abstract animal getAnimalByID( int _id)
     {
         // databse connection
         //get data from database and return an animal type
         return animal; <-- cannot work, "return this" can work
     }
} 

public class dog : animal
{
     public override dog getAnimalByID( int _id)
     {
          return (dog )base.getAnimalByID( _id);
     }
}

我有一个抽象基类,并从数据库中获取数据。狗比动物有更多的字段和函数,我想从数据库返回狗的数据类型。

问题1:

返回(狗)基数。返回访问基类错误

问题2:

(dog)也返回错误

继承后不能返回新的类类型

第一个类的方法不能声明为抽象如果我想在第二个类中使用

剩下的工作正常后,我拿走了抽象