如何在基类中创建对象的克隆? [英] How do I create clone of object in base class?

查看:154
本文介绍了如何在基类中创建对象的克隆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个在基类中创建对象的空克隆的方法吗?例如:

I need a method that creates an empty clone of an object in a base class? For instance:

public class ChildClass : ParentClass
{
   public ChildClass()
   {
   }
}
public class ParentClass
{
  public SomeMethod()
  {
     // I want to create an instance of the ChildClass here
  }
}

到目前为止,我们已经定义了一个抽象方法在父类中。并且,所有子类都实现它们。但是,所有实现都是相同的,只是一种不同的类型。

Up until now, we have an abstract method defined in the parent class. And, all of the child classes implement them. But, the implementation is the same for all, just a different type.

public class ChildClass : ParentClass
{
   public ChildClass()
   {
   }
   public ParentClass CreateEmpty()
   {
      return new ChildClass();
   }
}
public class ParentClass
{
  public SomeMethod()
  {
     // I want to create an instance of the ChildClass here
     ParentClass empty = CreateEmpty();

  }
  public abstract ParentClass CreateEmpty();
}

有什么方法可以从父类这样做,这样我就不会必须为每个不同的子类继续实现相同的逻辑吗?请注意,可能有更多级别的继承(即ChildChildClass:ChildClass:ParentClass)。

Is there any way to do this from the parent class so that I don't have to keep implementing the same logic for each different child class? Note that there may be more levels of inheritance (i.e. ChildChildClass : ChildClass : ParentClass).

推荐答案

如果使用反射不是问题,你可以使用Activator类来做:

If using reflection isn't a problem to you, you could do it using Activator class:


//In parent class
public ParentClass CreateEmpty()
{
    return (ParentClass)Activator.CreateInstance(this.GetType());
}

这将返回所需类型的空对象。请注意,此方法不需要是虚拟的。

This will return empty object of the type you want. Notice that this method does not need to be virtual.

另一方面,我认为您当前的方法非常好,几行代码也不是那么糟糕。

On the other hand, I think that your current approach is perfectly fine, few more lines of code aren't so bad.

这篇关于如何在基类中创建对象的克隆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆