对象分配 [英] object assignment

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

问题描述

我有这样一个场景:

MyClass obj1 = new MyClass();
............//some operations on obj1;
MyClass obj2 = new MyClass();
obj2 = obj1;



我有以下问题:如果我修改任何参数,它影响了两个对象(如既是指同一位置) - 但是,当我修改OBJ2参数,它不应该修改OBJ1该参数值(即意味着双方不应指向同一位置)。我该怎么办呢?请帮帮我。
作为MyClass的未实现ICloneable,我不能修改MyClass的我不能在这里克隆。
如果我通过序列化和反序列化克隆,会是一个深克隆?

I have the following problem: if I modify any parameter, it is affected in both objects (as both refer to same location) - but, when I modify obj2 parameter, it should not modify that parameter value in obj1 (i.e. means both should not point to same location). How can I do that? Please help me. I can't clone here as myclass is not implementing ICloneable and I can't modify myclass. if I clone by serializing and deserializing, will it be a Deep clone?

推荐答案

请您 MyClass的 ICloneable 并用

myclass obj1 = new myclass();
...
myclass obj2 = obj1.Clone();



(顺便说一句,该约定是使用的 驼峰线 Pascal大小写来命名类,即 MyClass的所以其他用户不会混淆它作为一个变量。)

(BTW, the convention is to use CamelCase Pascal case to name your class, i.e. MyClass so the other users won't confuse it as a variable.)

如果MyClass的不是可克隆,你需要查找所有在OBJ1特征值和将它们复制到OBJ2,如:

If myclass is not clonable, you need to look up all characteristic values in obj1 and copy them to obj2, e.g.

myclass obj2 = new myclass();
obj2.color = obj1.color; // .Clone();
obj2.size = obj1.size;
obj2.numberOfLimbs = obj1.numberOfLimbs;
// etc.

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

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