简体   繁体   中英

Deep Copy via copy constructor with a list of custom objects

I have some data members for my custom Rule object. A few integers, strings, DateTimes, all of which I have handled in the "Copy constructor" that you will see below. I have replaced the actual names of the data members for privacy.

public class Rule
{
    private int someint1;
    private int someint2;
    private string string1;
    private string string2;
    private List<Rule> children;

    public Rule(Rule other)
    {
        other = (Rule)this.MemberwiseClone(); //Handles my integers and DateTimes.
        other.string1 = String.Copy(string1);
        other.string2 = String.Copy(string2);
        //Now handle List<Rule> children;-----------
    }
}

My question is since I have a List with a recursive nature being in my Rule class. (A rule may have other rules...etc.) How might I handle a deep copy of that list of children(child Rules)? Do I need to foreach loop through and recall my copy constructor if the list is not empty?

**Should not be important, but I am populating this information from Sql rather than on the fly construction.

**Edit The question flagged as a potential duplicate does not address my issue of having a List in the CustomObj class. It addresses a List in a class that isn't its own type and therefore I believe this question deserves a separate question that is not a duplicate.

public class Rule
{
    private int someint1;
    private int someint2;
    private string string1;
    private string string2;
    private List<Rule> children;

    public Rule()
    {

    }

    public Rule(Rule other)
    {
        other = (Rule)this.MemberwiseClone(); //Handles my integers and DateTimes.
        other.string1 = String.Copy(string1);
        other.string2 = String.Copy(string2);
        other.children = children.Select(x => x.clone()).ToList();

    }
    public Rule clone()
    {
        Rule clone = new Rule();

        clone.children = this.children;

        return clone;

    }
}

public static class ExtentionAkrout {

            public static object CopyConstructAla(this object a,object b)
    {


        foreach (PropertyInfo propertyInfo in b.GetType().GetProperties())
        {
            PropertyInfo myPropInfo = a.GetType().GetProperty(propertyInfo.Name.ToString());
            if (myPropInfo != null &&  myPropInfo.PropertyType == propertyInfo.PropertyType)
                    myPropInfo.SetValue(a, propertyInfo.GetValue(b));

        }

        return a;
    }
}

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