Object Assignment

I have a script like:

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

I have the following problem: if I change any parameter, this is affected in both objects (since both belong to the same place) - but when I change the obj2 parameter, it should not change this parameter value in obj1 (i.e. means both must not point to the same place). How can i do this? Please help me. I cannot clone here, since myclass does not implement ICloneable, and I cannot change myclass. if I clone serialization and deserialization, will it be a Deep clone?

+3
source share
7 answers

Make your myclassimplemented iCloneable and use

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

(BTW, agreement must use Camelcase case, , .. myclass .)


myclass , obj1 obj2, .

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

, , - .

obj1 obj2 . , .

, obj1, obj2 .

, , , , ICloneable.

+3

myClass: GetDeepCopy obj GetDeepCopy.

- :
myclass obj1 = new myclass();
...
myclass obj2 = obj1.etDeepCopy();

+1

KennyTM, object Clone() . , . . KennyTM . . ICloneable.

Clone() :

public object Clone()
{ 
 Myclass obj=new Myclass();
 return obj;
}
0

, , , MemberwiseClone, .

MyClass obj = new MyClass();
// do your thing
MyClass objCopy = new MyClass();
objCopy.IamInt = obj.IamInt;
objCopy.IamString = obj.IamString;

Jon Skeet .

0

KennyTM . , , , , , , .

, , : Fasterflect DeepClone(). ; CIL, , .

0

MyClass ,

MyClass obj2=new MyClass(obj1).

, :

MyClass CopyMyClassObject(MyClass obj1)
{
    MyClass Result = new MyClass();
    Result.Value1 = obj1.Value1;
    Result.Value2 = obj1.Value2;
    //...
    Result Valuen = obj1.Valuen;
    Result.Object1.Value1 = obj1.Object1.Value1;
    Result.Object1.Value2 = obj1.Object1.Value2;
    //...
    Result.Object1.Valuen = obj1.Object1.Valuen;
    //..and so on until all values have been assigned
    //The actual assignments will use whatever methods are provided in MyClass, of course.
    return Result;
}

:

MyClass obj2 = CopyMyClassObject(obj1);

, .

0

Source: https://habr.com/ru/post/1737882/


All Articles