返回派生类实例的抽象方法

返回派生类实例的抽象方法

问题描述:

是否可以创建一个必须返回派生类实例的抽象方法?我可以这样做:

Is it possible to create an abstract method that must return an instance of the derived class? I can do this:

abstract class Base
{
   public abstract Base GetObj();
}

class Derived : Base
{
   public Derived() { }

   public override Base GetObj()
   {
       return new Derived();
   }
}

但我想知道是否有办法让 Derived::GetObj() 强制返回 Derived?

But I was wondering if there was a way to do it such that Derived::GetObj() is forced to return a Derived?

谢谢.

使用泛型应该可以:

abstract class Base<T>
    where T : Base<T>
{
   public abstract T GetObj();
}

class Derived : Base <Derived>
{
   public Derived() { }

   public override Derived GetObj()
   {
       return new Derived();
   }
}

您甚至可以进一步简化(如果所有派生实例都使用默认构造函数创建):

You could even simplify this even more (if all of the derived instances are created with default constructors):

abstract class Base<T>
    where T : Base<T>, new()
{
    public static T GetObj()
    {
        return new T();
    }
}

class Derived : Base<Derived>
{
    public Derived() { }
}