How to clone an inherited object?

后端 未结 3 1907
深忆病人
深忆病人 2021-01-22 08:24

I\'ve got a Tile class with this method:

    public object Clone()
    {
        return MemberwiseClone();
    }

And another class

3条回答
  •  花落未央
    2021-01-22 08:35

    Yes, MemberwiseClone will also copy the Checker-only fields. MemberwiseClone cannot know the return type of your Clone method; therefore, it's behaviour cannot depend on it.


    About the difference betweeen your Clone implementation and the serialization: MemberwiseClone creates a shallow copy of the Tiles: If a Tile (or Checker) references some object, the Tile's clone still references the same object (rather than a copy of it).

    On the other hand, your serialization code is a well known practice for creating a deep copy of your board: The whole tree of dependent objects is serialized and deserialized.

    Of course, this only makes a difference if your Tiles (or Checkers) contain fields with reference types.

提交回复
热议问题