How to clone an inherited object?

I have a class Tileusing this method:

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

And another class Checkerthat inherits from Tile.

I also have a class Boardthat is List<Tile>. I want to clone a board, so I wrote this:

    public Board Clone()
    {
        var b = new Board(width, height);
        foreach (var t in this) b.Add(t.Clone());
        return b;
    }

But this causes an error:

cannot convert from 'object' to 'Checkers.Tile'

Now I can force the method to Tile.Clonereturn Tileinstead, but then will MemberwiseClonecopy the additional properties into the sub Checker?


If this is not a problem, then what is the semantic difference between the above method Board.Cloneand this?

    public Board Clone()
    {
        using (var ms = new MemoryStream())
        {
            var bf = new BinaryFormatter();
            bf.Serialize(ms, this);
            ms.Position = 0;
            return (Board)bf.Deserialize(ms);
        }
    }

, , , . , - , . Board ctor :

    public Board(int width = 8, int height = 8)
    {
        this.width = width;
        this.height = height;
        this.rowWidth = width / 2;
        this.Capacity = rowWidth * height;
    }

Tile . :

public enum Color { Black, White };
public enum Class { Man, King };

public class Checker : Tile
{
    public Color Color { get; set; }
    public Class Class { get; set; }
+2
3

, MemberwiseClone Checker -only. MemberwiseClone Clone; .


: MemberwiseClone Tiles: Tile ( Checker) - , Tile - ( ).

, : .

, , ( ) .

+3

, :

  1. , , -
  2. , , MemberwiseClone
  3. , , , MemberwiseClone
  4. , .
, # 1 # 2, MemberwiseClone. № 3 -.

, CloneBase, Object, ( ); CloneBase MemberwiseClone , . , , Clone, CloneBase . , , CloneBase.

- , , - CloneableWhatever, , Clone. , - - , CloneableWhatever.

+2

Yes it will - it is polymorphism .

+1
source

Source: https://habr.com/ru/post/1763367/


All Articles