[英]How to get a object's copy
我有一個列表,類似於“ 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;
}
}
編輯:
OP誤以為新的Block
實例被從List<Block>
拔出,因為List<Rectangle>
沒有在復制構造函數中克隆,而是簡單分配,因此導致兩個唯一的Block
實例引用相同的List<Rectangle>
。
在這種情況下,正確的副本構造函數為:
public Block(Block originalBlock)
{
this._block = new List<Rectangle>(originalBlock.block);
this._blockNum = originalBlock.blockNum;
}
在Rectangle
類中需要類似的復制構造函數。
這應該為您工作:
public class Block
{
private List<Rectangle> _block;
public List<Rectangle> block
{
get { return _block; }
}
private int _blockNum;
public int blockNum
{
get { return _blockNum; }
}
// Copy constructor
public Block(Block originalBlock)
{
// IMPORTANT: This does not create a new List<Rectangle>! See EDIT
this._block = originalBlock.block;
this._blockNum = originalBlock.blockNum;
}
}
用法:
Block originalBlock = new Block();
// Returns a new instance of Block with similar member data.
Block copiedBlock = new Block(originalBlock);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.