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

五迷三道 提交于 2019-12-11 01:55:16

问题


What is the best way to copy a BindingList?

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


回答1:


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.




回答2:


Foreach pretty much is the easiest way, and the performance overhead is minimal if any.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/2757310/c-sharp-what-is-the-best-way-to-copy-a-bindinglist

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!