[英]C# What is the best way to copy a BindingList?
復制BindingList的最佳方法是什么?
只是使用ForEach()? 還是有更好的方法?
BindingList有一個可以接受IList的構造函數。 BindingList實現IList。 因此,您可以執行以下操作:
BindingList newBL = new BindingList(oldBL);
當然,這將創建僅指向相同對象的第二個列表。 如果您實際上要克隆列表中的對象,則必須做更多的工作。
最簡單的方法是Foreach,如果有的話,性能開銷也很小。
從已刪除的答案中:
序列化對象,然后反序列化以獲得深克隆的未引用副本
如果OP需要深拷貝,則這是一個有效的選擇。
我們使用序列化/反序列化路由來獲取列表的深層副本。 它運作良好,但是在較大的列表(例如搜索屏幕)中確實降低了性能,因此我避免在具有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.