2014-02-21 110 views
0

我有下面這段代碼:多個字段的值

public GameMenu(Scene startScene) 
{ 
    this.StartSceneBackup = startScene; 
    this.StartSceneBackup.Entities[0].X = 200; 

    this.StartScene = startScene; 
} 

的StartSceneBackup變量是從來不碰,只有StartScene變量被訪問,但是當我改變通過X的值this.StartSceneBackup.Entities[0].X = 200;它改變了值this.StartScene.Entities[0].X = 200;

這是爲什麼?

回答

2

因爲Scene是一個引用類型,所以StartSceneBackup和StartSceneBackup指向同一個對象。 關於引用類型REF http://msdn.microsoft.com/en-us/library/490f96s2.aspx

編輯

,如果你想保存一個備份副本,你應該明白淺克隆和深克隆,以供參考U型必須用深克隆,u能實現像在場景類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(); 
...