object assignment

前端 未结 7 1042
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-21 07:07

I have a scenario like:

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

I h

7条回答
  •  庸人自扰
    2020-12-21 07:48

    KennyTM's suggestion would be the default choice. However, since you can't modify the source as you mentioned in a comment, you may need to write much code, possibly reflection if private members are involved.

    If you can use an open-source library and if all types in the object graph of the to-be-cloned object have a default constructor, you can check out a utility in my library: Fasterflect's DeepClone(). This utility performs, no surprise, deep clone and handles cyclic references; the implementation is backed by CIL code generation, so no performance should be much better than hand-crafted reflection code.

提交回复
热议问题