如何使一个物体在C#中的副本 [英] How to make a copy of an object in c#

查看:126
本文介绍了如何使一个物体在C#中的副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说,我有一个类:

Let's say that I have a class:

class obj
{
  int a;
  int b;
}

然后我有这个code:

and then I have this code:

obj myobj = new obj(){ a=1, b=2}
obj myobj2 = myobj;

现在上面的code使得在第一的obj的参考。我想的是, myobj2 MyObj中的副本没有被反映在原始的变化。我已搜查SO和解决方案迄今看起来很复杂。是否有更简单的方法来做到这一点。我使用.NET 4.5

Now the above code makes a reference to the first obj. What I want is that myobj2 refers to a copy of the myobj with changes not being reflected in the original. I have searched SO and the solutions thus far seems complicated. Is there an easier way to do this. I am using .net 4.5

推荐答案

在你的对象属性是值类型,你可以在这样的sutuation使用浅拷贝这样的:

Properties in your object are value types and you can use shallow copy in such sutuation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

但在像如有成员是引用类型的其他情况,那么你需要深层复制。您可以使用此方法获取对象的深层副本:

But in other situations like if any members are reference types, then you need Deep Copy. You can get deep copy of object using this method:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

其他信息:(你也可以阅读这篇文章从<一个href=\"https://msdn.microsoft.com/en-us/library/system.object.memberwiseclone(v=vs.110).aspx\">MSDN)

Additional Info: (you can also read this article from MSDN)

浅拷贝是创建一个新的对象,然后复制当前对象的非静态字段的新对象。如果字段是值类型,一个逐位字段的副本进行;为引用类型,引用复制,但引用的对象不是;因此原始对象及其克隆指代相同的对象。

Shallow copying is creating a new object and then copying the non-static fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

深层复制是创建一个新的对象,然后复制当前对象的非静态字段的新对象。如果字段是值类型,执行逐位字段的副本。如果一个字段是引用类型,则引用的对象的新副本进行。

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

这篇关于如何使一个物体在C#中的副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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