Create an instance of derived class from the base class

我的未来我决定 提交于 2019-11-28 12:45:25

While I like Jamiec solution, I'm missing dirty solution using reflection :)

public class A {
  public object Clone() {
    var type = GetType().GetConstructor(new[] { typeof(int), typeof(int) });
    return type.Invoke(new object[] { this.Min, this.Max });
  }
}

Yes, this is possible with an abstract factory method on your base class

public abstract class A
{
   public int Min { get; protected set; }
   public int Max { get; protected set; }

   public A(int low, int high)
   {
       this.Min = low;
       this.Max = high;
   }
   protected abstract A CreateInstance(int low, int high);

   public object Clone()
   {
      return this.CreateInstance(this.Min,this.Max);
   }
}

public class B:A
{
   public B(int low, int high)
      : base(low,high)
   {
   }
   protected override A CreateInstance(int low, int high)
   {
      return new B(low,high);     
   }
}

This can be done and your current approach is a well defined design pattern, though most implementations make the Clone an abstract virtual method and override it in all subclasses.

public abstract class A
{
    public abstract A Clone( );
}

public class B : A
{
    public override A Clone( )
    {
        return new B( );
    }
}

public class C : A
{
    public override A Clone( )
    {
        return new C( );
    }
}

Since you are using C# you could make use of the Activator class. You can make the Clone method virtual (not === abstract) with a default implementation of.

public abstract class A
{
    public virtual A Clone( )
    {
        // assuming your derived class contain a default constructor.
        return (A)Activator.CreateInstance(this.GetType( ));
    }
}

Edit - If you do not have a default parameter-less constructor in all of your derived classes, you can add parameters to the Activator.CreateInstance method

(A)Activator.CreateInstance(this.GetType( ), this.Min, this.Max);

For varying constructors on the derived types I would recommend you override the Clone method specifically for those types instead of using the default implementation of Clone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!