How to Clone Objects

后端 未结 13 1258
北海茫月
北海茫月 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:09

    a and b are just two references to the same Person object. They both essentially hold the address of the Person.

    There is a ICloneable interface, though relatively few classes support it. With this, you would write:

    Person b = a.Clone();
    

    Then, b would be an entirely separate Person.

    You could also implement a copy constructor:

    public Person(Person src)
    {
      // ... 
    }
    

    There is no built-in way to copy all the fields. You can do it through reflection, but there would be a performance penalty.

提交回复
热议问题