【问题标题】:clone class in constructor在构造函数中克隆类
【发布时间】:2012-12-28 01:03:43
【问题描述】:

我需要类似的东西

public class  object_t 
{

    public object_t ( string config, object_t default_obj )
    {
         if( /*failed to initialize from config*/ )
         { 
            this = default_obj; // need to copy default object into self
         }
    }
 }

我知道这是不正确的。如何实现这个构造函数?

【问题讨论】:

标签: c#


【解决方案1】:

最常见的可能是使用静态工厂方法:

public class object_t 
{    
    public static object_t CreateObjectT(string config, object_t default_obj)
    {
         object_t theconfiguredobject = new object_t();

         //try to configure it

         if( /*failed to initialize from config*/ )
         { 
             return default_obj.Clone();
         }
         else
         {
             return theconfiguredobject;
         }
    }
}

完成上述操作的更好方法是创建一个复制构造函数:

public object_t (object_t obj)
    : this()
{
    this.prop1 = obj.prop1;
    this.prop2 = obj.prop2;
    //...
}

以及一个尝试从配置字符串创建对象的方法:

private static bool TryCreateObjectT(string config, out object_t o)
{
    //try to configure the object o
    //if it succeeds, return true; else return false
}

然后让你的工厂方法先调用 TryCreateObjectT,如果失败,复制构造函数:

public static object_t CreateObjectT(string config, object_t default_obj)
{
     object_t o;
     return TryCreateObjectT(config, out o) ? o : new object_t(default_obj);
}

【讨论】:

  • 我真的需要克隆默认对象,因为新对象将来可能会覆盖某些字段。您的 CreateObjectT 只是返回对默认对象的引用。因此任何字段更改都会影响默认对象。
  • @Newbee 好的,我添加了对Clone() 的调用——你也可以在这里使用复制构造函数。 (另请参阅第二个/扩展建议)
【解决方案2】:

您应该将每个字段从默认对象复制到构造函数中的新对象:

public class  object_t 
{ 
    int A, B;

    public object_t ( string config, object_t default_obj )
    {
         if( /*failed to initialize from config*/ )
         { 
            this.A = default_obj.A; 
            this.B = default_obj.B; 
            //...
         }
    }
}

但是你应该记住,如果这个类的字段是引用类型,你也必须Clone它们,而不仅仅是分配一个引用。

这种方法确实会创建默认对象的副本,而如果您只需要返回默认对象本身,则应该使用 lc 提到的工厂方法。

【讨论】:

  • @Newbee 但是您需要以某种方式将值从默认对象复制到新对象。当然,您可以使用 Reflection 和一个 for-loop 来执行此操作,但在此之前请考虑 十次 次。
  • 查看C# Using Reflection to copy base class properties 帖子,了解如何使用反射实现此目的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多