[英]How to deep copy a matrix in C#?
我有一个List<List<CustomClass>>
,其中CustomClass
是一个引用类型。
我需要将这个矩阵的完整深度复制到一个新的矩阵中。 由于我需要深层复制,因此必须将矩阵中的每个CustomClass对象复制到新矩阵中。
你会如何以有效的方式做到这一点?
对于实现ICloneable的CustomClass,这不是很困难:
var myList = new List<List<CustomClass>>();
//populate myList
var clonedList = new List<List<CustomClass>>();
//here's the beef
foreach(var sublist in myList)
{
var newSubList = new List<CustomClass>();
clonedList.Add(newSubList);
foreach(var item in sublist)
newSublist.Add((CustomClass)(item.Clone()));
}
如果你觉得你不想实现ICloneable,我可以用任何“DeepCopy”类型的方法以类似的方式工作(我建议使用内置接口)。
序列化整个对象然后再次反 序列化的一种更简单的方法是尝试这种扩展方法:
public static T DeepClone<T>(this T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
用法
List<List<CustomClass>> foobar = GetListOfListOfCustomClass();
List<List<CustomClass>> deepClonedObject = foobar.DeepClone();
有两种可能性:
在CustomClass上实现ICloneable接口,然后您可以克隆您的对象。
如果可以序列化类,则将其序列化为内存流并从那里反序列化。 这将创建它的副本。
我更愿意选择第一种方法,因为我认为序列化/反序列化比通过ICloneable进行克隆要慢。
假设您有一个可以复制CustomClass
对象的Copy
方法:
var newMatrix = oldMatrix
.Select(subList => subList.Select(custom => Copy(custom)).ToList())
.ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.