Best way to create instance of child object from parent object

前端 未结 7 567
萌比男神i
萌比男神i 2020-12-11 00:04

I\'m creating a child object from a parent object. So the scenario is that I have an object and a child object which adds a distance property for scenarios where I want to s

7条回答
  •  眼角桃花
    2020-12-11 00:51

    If a shallow copy is enough, you can use the MemberwiseClone method.

    Example:

    MyObject shallowClone = (MyObject)original.MemberwiseClone();
    

    If you need a deep copy, you can serialize/deserialize like this: https://stackoverflow.com/a/78612/1105687

    An example (assuming you write an extension method as suggested in that answer, and you call it DeepClone)

    MyObject deepClone = original.DeepClone();
    

提交回复
热议问题