[英]What is the fastest way to clone object several times
I need to clone pretty big object several times and I am finding the faster way to do it. 我需要多次克隆相当大的对象,因此我找到了更快的方法。
Now I use serialization by BinaryForamter
into MemoryStream
. 现在,我使用
BinaryForamter
序列化到MemoryStream
。 So here is how I would like to use feature I am speaking about ( DeserializeToList
is method I am looking for): 因此,这就是我要使用的功能(
DeserializeToList
是我正在寻找的方法):
var originalObject = new MyClass();
var objectClones = new List<MyClass>();
var cloneCount = 10;
var formatter = new BinaryFormatter();
using (var stream = new MemoryStream())
{
formatter.Serialize(stream, originalObject);
stream.Seek(0, SeekOrigin.Begin);
objectClones = (MyClass)formatter.DeserializeToList(formatter, cloneCount);
}
Does anybody have any ideas? 有人有什么想法吗?
UPDATE: 更新:
I don't want to change MyClass
. 我不想更改
MyClass
。 That's why I use binary serialization. 这就是为什么我使用二进制序列化。 So
MyClass.Clone
isn't solution for now. 所以
MyClass.Clone
暂时不是解决方案。
UPDATE 2: 更新2:
I don't want to even touch MyClass
or them properties. 我什至不想触摸
MyClass
或它们的属性。 So manually properties copying isn't way I am looking for. 因此,手动属性复制不是我想要的方法。
You can use extension methods for this purpose if you don't want to touch the original class. 如果您不想触摸原始类,则可以为此使用扩展方法。
public class MyClass
{
public string Name { get; set; }
}
public static class MyClassExtensions
{
public static MyClass Clone(this MyClass obj)
{
return new MyClass()
{
Name = obj.Name
};
}
}
And then use it like: 然后像这样使用它:
var originalObj = new MyClass() { Name = "Original" };
var clonedObj = originalObj.Clone();
Console.WriteLine(clonedObj.Name); // Name = "Original"
I didn't test about the benchmark's performance, but why don't implement Clone interface? 我没有测试基准性能,但是为什么不实现Clone接口呢?
public interface ICloneable<T>
{
T Clone();
}
public class ComplessObj : ICloneable<Book>
{
public string f1;
public int f2;
.. and so on
public ComplessObj Clone()
{
return new ComplessObj { /* set properties f1,f2 ..*/ };
}
}
and every time you want deep clone list of your complex object 以及每次您想要复杂对象的深层克隆列表时
You can use LINQ 您可以使用LINQ
List<ComplessObj> ComplessObj_2 = ComplessObj.Select(co => co.Clone()).ToList();
or 要么
List<ComplessObj> ComplessObj_2 = ComplessObj.ConvertAll(co => co.Clone());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.