2011-01-29 4 views
0

에 추가 I는 다음과 같습니다 몇 가지 코드가 있습니다는 요소는 또 다른 사전 (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)); } 
    } 
} 

내가 디버그에있는 코드를 보면서을 나는 oldGamePadState.Add (...)를 호출하지 않았지만, gamePadState.Add (...);라고도 불렀다.

답변

2

난 당신 만 실제로 한 사전을 가지고 의심, 당신은

Control.oldGamePadState = Control.gamePadState; 

(또는 그 반대)를하고있다 어딘가에 몇 가지 코드를 가지고있다. 복사합니다 참조을, 그 문 다음에 그들이 모두 같은 사전을 참조 할 것 - 그래서 다른 하나 개의 변수에서 사전 객체를 복사하지 않습니다

. 놀람이라면 article on reference types and value types을 읽어보십시오.

Phil이 말한 것처럼, 비공개로 설정하는 것이 좋습니다. 또한 변수를 읽기 전용으로 설정하는 것이 좋습니다. 그러면 사전을 읽기 전용으로 만들지 않으므로 변수가 다시 할당되는 것을 막을 수 있습니다.

+0

이 경우인지 확인하려면'.Add()'줄에 중단 점을 넣고 Object.ReferenceEquals()를 평가하십시오 (http://msdn.microsoft.com/en-us/library/system.object .referenceequals.aspx)를 사용하여 두 사전 참조가 같은지 확인하십시오. – Bevan

4

다른 곳에서 코드를 사용하여 사전에 항목을 추가 할 가능성이 매우 높습니다. 나는 그들이 모두 공개다는 것을 본다. 아마도 그것들을 비공개로 만들고 래퍼 메서드를 통해서만 사전 메서드를 노출시키는 것이 좋을 것입니다. 그런 다음 해당 래퍼 메서드에 중단 점을 설정하여 다른 코드가 사전에 액세스하고 있는지 확인할 수 있습니다. 예를 들어

:

가 공용 속성이 아니라 일반 세 공용 변수보다 (getter 및 setter)를 사용하는 것은 일반적으로 좋은 생각하는 이유에 대한 자세한 내용은
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; 
    } 
} 

, this stackoverflow answer를 참조하십시오.