如何克隆对象 [英] How to Clone Objects

查看:136
本文介绍了如何克隆对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我做下面的事情..做某乙改变一个人(我以为这样做会克隆从人,将B)。我也有改变,如果一个人将在联后改变某乙不知道。由于我的code现在,我只能看到这1个方向。

 一个人=新的Person(){头=大,脚=小};
人B = A;b.head =小; //现在a.head =小太

现在如果我这样做,而不是..一个人变得完全独立。

 某乙=新的Person(){头= a.head,脚= a.feet};

相比这种行为给其他的东西在C#中,当现在,这很好,还挺有道理。但是,这可以得到非常恼人的大型物体。

有没有办法在所有快捷方式呢?

如:

某乙= a.Values​​;


解决方案

  

有没有办法来缩短这一可言?


没有,真的没有。你需要做一个新的实例,以避免影响复制原件。有几个选项为此:


  1. 如果你的类型是一个结构,而不是,将通过值被复制(而不是仅仅复制引用实例)。这将给它您所描述的语义,但还有许多其他副作用,往往不太理想,因此不推荐任何可变类型(这显然是,或者这会不会是一个问题!)


  2. 实现你的类型,以克隆的机制。这可以是 ICloneable 或甚至只是一个构造,从它需要一个实例,并拷贝值。


  3. 使用反射,MemberwiseClone,或类似的跨复制所有值,因此您不必写code做到这一点。这有潜在的问题,特别是如果你有一个包含非简单类型的字段。


When I do the following.. anything done to Person b modifies Person a (I thought doing this would clone Person b from Person a). I also have NO idea if changing Person a will change Person b after the linking. Due to my code right now, I can only see this in 1 direction.

Person a = new Person() { head = "big", feet = "small" };
Person b = a; 

b.head = "small"; //now a.head = "small" too   

Now if I do this instead.. Person a becomes completely separate.

Person b = new Person() { head = a.head, feet = a.feet };

Now this fine and kinda makes sense when comparing this behaviour to other things in C#. BUT, this could get very annoying with large objects.

Is there a way to shortcut this at all?

Such as:

Person b = a.Values;

解决方案

Is there a way to shortcut this at all?

No, not really. You'll need to make a new instance in order to avoid the original from affecting the "copy". There are a couple of options for this:

  1. If your type is a struct, not a class, it will be copied by value (instead of just copying the reference to the instance). This will give it the semantics you're describing, but has many other side effects that tend to be less than desirable, and is not recommended for any mutable type (which this obviously is, or this wouldn't be an issue!)

  2. Implement a "cloning" mechanism on your types. This can be ICloneable or even just a constructor that takes an instance and copies values from it.

  3. Use reflection, MemberwiseClone, or similar to copy all values across, so you don't have to write the code to do this. This has potential problems, especially if you have fields containing non-simple types.

这篇关于如何克隆对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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