通用的方法集合中创建的所有元素的深层副本 [英] Generic method to create deep copy of all elements in a collection

查看:124
本文介绍了通用的方法集合中创建的所有元素的深层副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有不同的对象类型的各种ObservableCollections。我想写其中每个元素是给定的集合中元素的深层副本,将采取任何这些对象类型的集合,并返回一个新的集合一个方法。下面是一个例子了specifc类

I have various ObservableCollections of different object types. I'd like to write a single method that will take a collection of any of these object types and return a new collection where each element is a deep copy of elements in the given collection. Here is an example for a specifc class

   private static ObservableCollection<PropertyValueRow> DeepCopy(ObservableCollection<PropertyValueRow> list)
   {
        ObservableCollection<PropertyValueRow> newList = new ObservableCollection<PropertyValueRow>();
        foreach (PropertyValueRow rec in list)
        {
            newList.Add((PropertyValueRow)rec.Clone());
        }
        return newList;
   }

我怎样才能使这种方法一般用于其实现ICloneable任何一类?

How can I make this method generic for any class which implements ICloneable?

推荐答案

您可以做这样的事情:

private static ObservableCollection<T> DeepCopy<T>(ObservableCollection<T> list)
    where T : ICloneable
{
   ObservableCollection<T> newList = new ObservableCollection<T>();
   foreach (T rec in list)
   {
       newList.Add((T)rec.Clone());
   }
   return newList;
}

请注意,你可以使这个更普遍采取的IEnumerable&LT; T&GT; 和LINQ使得它更容易:

Note that you could make this more general by taking IEnumerable<T>, and LINQ makes it even easier:

private static ObservableCollection<T> DeepCopy<T>(IEnumerable<T> list)
    where T : ICloneable
{
   return new ObservableCollection<T>(list.Select(x => x.Clone()).Cast<T>());
}

这篇关于通用的方法集合中创建的所有元素的深层副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆