2011-08-30 6 views
2

C#에서는 get/setter가없는 변수를 가져 오기 위해 리플렉션을 어떻게 사용합니까? 예를 들어 아래의 getValue 메소드는 d2에서는 작동하지만 d1에서는 작동하지 않습니다.C# 리플렉션을 사용하여 필드 가져 오기

public class Foo { 

    public String d1; 
    public String d2 { get; set; } 

    public object getValue(String propertyName){ 
     return this.GetType().GetProperty(propertyName).GetValue(this, null); 
    } 
} 
+7

, 그들은 특성 아니에요. 그것들은 들판입니다. 그들은 같은 것이 아닙니다. –

답변

9

d1는 (는) 재산이 아닙니다. 그것은 분야입니다. 대신 필드에 반사 방법을 사용하십시오.

public class Foo { 

    public String d1; 
    public String d2 { get; set; } 

    public object getValue(String propertyName){ 
     var member = this.GetType().GetMember(propertyName).Single(); 
     if (member is PropertyInfo) 
     { 
      return ((PropertyInfo)member).GetValue(this, null); 
     } 
     else if (member is FieldInfo) 
     { 
      return ((FieldInfo)member).GetValue(this); 
     } 
     else throw new ArgumentOutOfRangeException(); 
    } 
} 
+0

당신이 사용한'GetMember'의 [overload] (http://msdn.microsoft.com/en-us/library/xdtchs6z.aspx)는 콜렉션을 리턴하지 않으므로'Single'은 필요 없습니다. – vcsjones

+0

@vcsjones : 실제로 배열을 반환합니다 (제공 한 링크 참조). 같은 이름의 멤버 (메서드)를 여러 개 가질 수 있습니다. 따라서 명명 규칙을 위반하더라도 GetMember는 여전히 컬렉션을 반환해야합니다. – StriplingWarrior

+1

Gha. 나는 심지어 내 자신의 종말과 관련이있다. 읽기가 실패했습니다. 나는 그것이'GetProperty' (배열을 반환하지 않음)와'GetProperties' (그럴 경우)와 동등하다고 잘못 가정했습니다. – vcsjones

4

d1는 (는) 재산이 아닙니다. 그것은 하나의 필드입니다. 리플렉션을 통해 검색하려면 this.GetType().GetField을 사용합니다. 당신은 아마 getValue이 속성 또는 필드의 값을 반환 할 것입니다하려는 어떤

public object getFieldValue(String fieldName){ 
    return this.GetType().GetField(fieldName).GetValue(this); 
} 

. GetMember은 속성인지 필드인지 알려줍니다. 예 :

public object getValue(String memberName) { 
    var member = this.GetType().GetMember(memberName).Single(); 
    if (member.MemberType == MemberTypes.Property) { 
     return ((PropertyInfo)member).GetValue(this, null); 
    } 
    if (member.MemberType == MemberTypes.Field) { 
     return ((FieldInfo)member).GetValue(this); 
    } 
    else 
    { 
     throw new Exception("Bad member type."); 
    } 
} 
관련 문제