在构造函数中克隆类

本文关键字:构造函数 | 更新日期: 2023-09-27 17:49:38

我需要像

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
         }
    }
 }

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

在构造函数中克隆类

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

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);
}

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

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中提到的工厂方法。