2011-01-29 104 views
0

我有一些代碼,看起來像這樣:當我元素添加到詞典時,該元素也添加到另一個字典(C#+ XNA)

public static class Control 
{ 
    public static Dictionary<PlayerIndex, GamePadState> gamePadState = new Dictionary<PlayerIndex,GamePadState>(); 
    public static Dictionary<PlayerIndex, GamePadState> oldGamePadState = new Dictionary<PlayerIndex, GamePadState>(); 

    public static void UpdateControlls() 
    { 
     gamePadState.Clear(); 
     foreach (PlayerIndex pIndex in pIndexArray) 
     { gamePadState.Add(pIndex,GamePad.GetState(pIndex)); } 
    } 
} 

正如我通過在調試,當代碼看上去我稱gamePadState.Add(...);它也添加到oldGamePadState,即使我從來沒有調用oldGamePadState.Add(...);

回答

2

我懷疑你只實際上有一個字典,和你有一些代碼的地方這是做

Control.oldGamePadState = Control.gamePadState; 

(反之亦然)。

這並不字典對象從一個變量複製到另一個 - 它複製參考,使語句之後他們會被都指的是相同的字典。如果您對此感到驚訝,請閱讀我的article on reference types and value types。正如菲爾所說,你應該考慮讓它們變成私人的,而且我也建議你只將變量只讀​​。這不會使得字典是隻讀的 - 它只會阻止變量被重新分配。

+0

要驗證是否出現這種情況,請在`.Add()`行上放置一個斷點並評估Object.ReferenceEquals()(http://msdn.microsoft.com/zh-cn/library/system.object .referenceequals.aspx)在調試器中查看兩個字典引用是否相同。 – Bevan 2011-01-29 08:00:36

4

機會很好,你有其他地方的代碼添加項目到你的字典。我看到他們都是公開的。也許最好讓它們變成私有的,只通過包裝器方法暴露字典方法。然後你可以在這些包裝方法中設置一個斷點來找出其他代碼訪問你的字典。

例如:

public static class Control 
{ 
    //Change these to private 
    private static Dictionary<PlayerIndex, GamePadState> gamePadState = new Dictionary<PlayerIndex,GamePadState>(); 
    private static Dictionary<PlayerIndex, GamePadState> oldGamePadState = new Dictionary<PlayerIndex, GamePadState>(); 

    public void AddOld(PlayerIndex index, GamePadState state) 
    { 
     oldGamePadState[index] = state; // Set breakpoint here 
     // When the breakpoint trips, look at the stack trace to find out 
     // who is calling this method 
    } 

    public void AddNew(PlayerIndex index, GamePadState state) 
    { 
     gamePadState[index] = state; 
    } 
} 

有關爲什麼它通常是使用公共屬性(getter和setter),而不是普通老式公共變量是一個好主意的詳細信息,請參閱this stackoverflow answer