Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
431 views
in Technique[技术] by (71.8m points)

c# - object assignment

I have a scenario like:

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Make your MyClass implement ICloneable and use

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

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...