简体   繁体   中英

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

What is the best way to copy a BindingList?

Just use ForEach()? Or are there better ways?

BindingList has a constructor which can take an IList. And BindingList implements 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.

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.

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

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