我的代码如下:
public GameMenu(Scene startScene)
{
this.StartSceneBackup = startScene;
this.StartSceneBackup.Entities[0].X = 200;
this.StartScene = startScene;
}
永远不会触及StartSceneBackup变量,只访问StartScene变量,但是当我通过this.StartSceneBackup.Entities[0].X = 200;
更改X的值时,它会更改this.StartScene.Entities[0].X = 200;
的值
为什么会这样?
答案 0 :(得分:2)
因为Scene是引用类型,StartSceneBackup和StartSceneBackup指向同一个对象。 关于参考类型参考http://msdn.microsoft.com/en-us/library/490f96s2.aspx
修改
如果你想保存备份副本,你应该了解Shallow Clone和Deep Clone,对于引用类型你必须使用深度克隆,你可以像这样在Scene类中实现ICloneable接口
public class Scene : ICloneable
{
/// your codes
public object Clone()
{
// it is DEEP CLONE
using (var stream = new MemoryStream())
{
var formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Position = 0;
return (Scene)formatter.Deserialize(stream);
}
}
}
和
public GameMenu(Scene startScene)
{
this.StartSceneBackup = startScene.Clone();
...