How to Clone Objects

后端 未结 13 1201
北海茫月
北海茫月 2020-11-30 04:36

When I do the following.. anything done to Person b modifies Person a (I thought doing this would clone Person b from Person a). I also have NO idea if changing Person a wil

相关标签:
13条回答
  • 2020-11-30 05:17

    Is there a way to shortcut this at all?

    No, not really. You'll need to make a new instance in order to avoid the original from affecting the "copy". There are a couple of options for this:

    1. If your type is a struct, not a class, it will be copied by value (instead of just copying the reference to the instance). This will give it the semantics you're describing, but has many other side effects that tend to be less than desirable, and is not recommended for any mutable type (which this obviously is, or this wouldn't be an issue!)

    2. Implement a "cloning" mechanism on your types. This can be ICloneable or even just a constructor that takes an instance and copies values from it.

    3. Use reflection, MemberwiseClone, or similar to copy all values across, so you don't have to write the code to do this. This has potential problems, especially if you have fields containing non-simple types.

    0 讨论(0)
提交回复
热议问题