簡體   English   中英

通過帶有自定義對象列表的復制構造函數進行深度復制

[英]Deep Copy via copy constructor with a list of custom objects

我的自定義Rule object 有一些數據成員。 一些整數、字符串、日期時間,所有這些我都在“復制構造函數”中處理過,您將在下面看到。 為了隱私,我已經替換了數據成員的實際名稱。

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

我的問題是因為我的規則 class 中有一個具有遞歸性質的列表。 (一條規則可能有其他規則……等等。)我如何處理該子項列表的深層副本(子規則)? 如果列表不為空,我是否需要 foreach 循環並調用我的復制構造函數?

**應該不重要,但我是從 Sql 而不是即時構建中填充此信息。

**編輯標記為潛在重復的問題不能解決我在 CustomObj class 中有一個列表的問題。 它解決了 class 中不是它自己的類型的列表,因此我相信這個問題值得一個單獨的問題,而不是重復的。

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;

    }
}

公共 static class 擴展Akrout {

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM