简体   繁体   中英

clone class in constructor

I need something like

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

I know this is not correct. How to implement this constructor ?

The most common is probably to use a static factory method:

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

A better way to do the above would be to create a copy constructor:

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

and a method that tries to create your object from the config string:

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

then have your factory method call the TryCreateObjectT first, and if it fails, the copy constructor:

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

You should copy each field from the default object to the new one within the constructor:

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; 
            //...
         }
    }
}

However you should remember, if this class' fields are reference types, you'll have to Clone them as well, not just assign a refernce to.

This approach does create a copy of the default object, while if you only need to return the default object itself, you should use the factory approach, mentioned by lc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM