2010-07-17 3 views
1

Interlocked.Increment를 사용하여 개체의 정수 멤버를 증가 시키길 원하지만 리플렉션을 통해 해당 정수를 참조하고자합니다. 아래 코드는 작동하지 않는 예제 코드입니다.연동 됨. 반영된 값 유형의 증가

public class StatBoard 
{ 

    #region States (count of) 
    public int Active; 
    public int Contacting; 
    public int Polling; 
    public int Connected; 
    public int Waiting; 
    public int Idle; 
    #endregion 

    protected IEnumerable<FieldInfo> states; 

    public StatBoard() 
    { 
     Type foo = GetType(); 
     FieldInfo[] fields = foo.GetFields(BindingFlags.Instance & BindingFlags.Public); 

     states = from n in fields 
        where n.FieldType == typeof(int) 
        select n; 

    } 

    public void UpdateState(string key) 
    { 
     FieldInfo statusType = states.First( 
      i => i.Name == key 
     ); 

     System.Threading.Interlocked.Increment(ref (int)statusType.GetValue(this)); 
    } 

} 

이 작업을 수행하려면 어떻게 UpdateState 메서드를 수정해야합니까?

+0

잠금/모니터를 처음 사용하지 않는 이유는 무엇입니까? 리플렉션을 수행하는 경우 Interlocked.Increment()의 성능 이점은 보이지 않을 수도 있습니다. 게다가 다른 사람이 같은 변수를 수정하거나 (예를 들어 리플렉션 없음) 동시에 (자물쇠에 관계없이) 수정할 수 있는지 확인할 수 없습니다. –

답변

1

이것은 의도적으로 작동하지 않을 수 있습니다. int는 값 유형입니다. GetValue() 메서드는 int의 복사본을 반환합니다. 원본이 아닌 사본을 증가시킵니다. 리플렉션은 값 유형 값에 대한 참조를 얻을 수있는 방법이 없습니다.

+1

그는 DynamicMethod에서 'Reflection.Emit'을 사용하여 필드 유형에 액세스 할 수 있습니다. 그것은 복잡하고 느릴 것입니다. –