简体   繁体   English

C#复制绑定列表的最佳方法是什么?

[英]C# What is the best way to copy a BindingList?

What is the best way to copy a BindingList? 复制BindingList的最佳方法是什么?

Just use ForEach()? 只是使用ForEach()? Or are there better ways? 还是有更好的方法?

BindingList has a constructor which can take an IList. BindingList有一个可以接受IList的构造函数。 And BindingList implements IList. BindingList实现IList。 So you can just do the following: 因此,您可以执行以下操作:

BindingList newBL = new BindingList(oldBL);

Of course that creates a second list that just points at the same objects . 当然,这将创建仅指向相同对象的第二个列表。 If you actually want to clone the objects in the list then you have to do more work. 如果您实际上要克隆列表中的对象,则必须做更多的工作。

最简单的方法是Foreach,如果有的话,性能开销也很小。

From a deleted answer: 从已删除的答案中:

Serialize the object then de-serialize to get a deep cloned non referenced copy 序列化对象,然后反序列化以获得深克隆的未引用副本

Which is a valid option if the OP wants a deep copy. 如果OP需要深拷贝,则这是一个有效的选择。

We use the Serialize / De-serialize route to get a deep copy of the list. 我们使用序列化/反序列化路由来获取列表的深层副本。 It works well but it does slow performance down in larger lists, such as for search screens, so I'd avoid using it on lists with 5000+ items. 它运作良好,但是在较大的列表(例如搜索屏幕)中确实降低了性能,因此我避免在具有5000多个项目的列表中使用它。

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace ProjectName.LibraryName.Namespace
{
    internal static class ObjectCloner
    {
        /// 
        /// Clones an object by using the .
        /// 
        /// The object to clone.
        /// 
        /// The object to be cloned must be serializable.
        /// 
        public static object Clone(object obj)
        {
            using (MemoryStream buffer = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(buffer, obj);
                buffer.Position = 0;
                object temp = formatter.Deserialize(buffer);
                return temp;
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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