对象分配
我有这样一个场景:
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.