【问题标题】:Copying List Objects C# [duplicate]复制列表对象 C# [重复]
【发布时间】:2018-11-14 04:16:31
【问题描述】:

我有两个列表对象,我正在尝试将一个列表的值复制到另一个列表中。理想的编码是这样的:

            List<List<int>> x = new List<List<int>>();
            List<int> temp = new List<int>();
            List<List<int>> y = new List<List<int>>();

            int myCount;


                foreach (List<int> t in y)
                {
                    myCount = t.Count;
                    for(int w = 0; w <= t.Count; w++)
                    {
                        temp = new List<int>();
                        temp = t;
                        temp.Insert(w,n);
                        x.Add(temp);
                    }
                }

显然,temp = t;不会是值副本,但是让这个赋值成为值副本而不是引用副本的最简单方法是什么。

我尝试了 t.ToList(),但智能感知没有看到(MSN 帮助页面上的列表定义中也没有列出)。我尝试了“MemberwiseClone”,但这也没有在智能感知中公开。像这样的时候我会错过指针...... :)

【问题讨论】:

  • 你是对的 - 找到了其他让我失望的线程。那个有帮助。谢谢。

标签: c#


【解决方案1】:
 public static T DeepClone<T>(T obj)
    {
        using (var ms = new MemoryStream())
        {
            var formatter = new BinaryFormatter();
            formatter.Serialize(ms, obj);
            ms.Position = 0;

            return (T)formatter.Deserialize(ms);
        }
    }
temp = DeepClone(t);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-21
    • 2012-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多