猿问

如何获得对象的副本

我有一个列表,类似这样的“ List <Block>”。我想要的是获得一个与列表中的块相同的块,而不是列表中的对象。并用块修改圆顶并获得另一个。


但是问题是,在获取了三次块(列表的长度为3)之后,第四个块已经被修改。我尝试了我所知道的所有方法,甚至使用“ new”,它只是将对象添加到列表中,而不是同一对象。


那么如何解决呢?


这是我的一些代码:


//This is the list which length is 3

private List<BlockType> blocks;


//At the beginning it was like this but not work

//private List<Block> blocks;


//In a function to get a block type randomly

int blockNum = rand.Next(0, 3); //rand is a Random type

this.cBlock = new Block(blocks[blockNum]); //cBlock is object which I use to do something about the block


//The class Block goes to

class Block

{

    private List<Rectangle> _block;

    public List<Rectangle> block

    {

        get { return _block; }

    }


    private int _blockNum;

    public int blockNum

    {

        get { return _blockNum; }

    }


    public Block()

    {


    }


    public Block(int blockNum, List<Rectangle> block)

    {

        this._block = block;

        this._blockNum = blockNum;

    }


    public Block(BlockType block)

    {

        this._block = block.block;

        this._blockNum = block.blockNum;

    }

}


//And the BlockType is what I tried but does not work

class BlockType

{

    private List<Rectangle> _block;

    public List<Rectangle> block

    {

        get { return _block; }

    }


    private int _blockNum;

    public int blockNum

    {

        get { return _blockNum; }

    }


    public BlockType()

    {


    }


    public BlockType(int blockNum, List<Rectangle> block)

    {

        this._block = block;

        this._blockNum = blockNum;

    }

}



慕慕森
浏览 133回答 1
1回答

桃花长相依

编辑:OP被误以为是一个新实例,因为它没有在复制构造函数中克隆,而是被简单地分配了,因此Block被引出了一个实例,因此导致两个唯一的实例引用同一个实例。List<Block>List<Rectangle>BlockList<Rectangle>在这种情况下,正确的副本构造函数将是:public Block(Block originalBlock){&nbsp; &nbsp; this._block = new List<Rectangle>(originalBlock.block);&nbsp; &nbsp; this._blockNum = originalBlock.blockNum;}在Rectangle类中需要类似的复制构造函数。这应该为您工作:public class Block{&nbsp; &nbsp; private List<Rectangle> _block;&nbsp; &nbsp; public List<Rectangle> block&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return _block; }&nbsp; &nbsp; }&nbsp; &nbsp; private int _blockNum;&nbsp; &nbsp; public int blockNum&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; get { return _blockNum; }&nbsp; &nbsp; }&nbsp; &nbsp; // Copy constructor&nbsp; &nbsp; public Block(Block originalBlock)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // IMPORTANT: This does not create a new List<Rectangle>! See EDIT&nbsp; &nbsp; &nbsp; &nbsp; this._block = originalBlock.block;&nbsp; &nbsp; &nbsp; &nbsp; this._blockNum = originalBlock.blockNum;&nbsp; &nbsp; }}用法:Block originalBlock = new Block();// Returns a new instance of Block with similar member data.Block copiedBlock = new Block(originalBlock);
随时随地看视频慕课网APP
我要回答