2012-09-04 2 views
3

의 메소드를 호출. 일부 특정 속성은 특성으로 장식되어 있습니다. 예를 들어 :필터 속성과 내가 그것을 몇 가지 특성을 가진 클래스가 재산

나는이 클래스의 모든 내 속성을 통해 안내 내 클래스의 메소드를 갖고 싶어
public class CoreAddress 
{ 
    private ContactStringProperty _LastName; 

    [ChangeRequestField] 
    public ContactStringProperty LastName 
    { 
     //ContactStringProperty has a method SameValueAs(ContactStringProperty other) 
     get { return this._LastName; } 
    } 
    ..... 
} 

이 사용자 지정 특성을 가진 하나를 필터링하고 발견 된 속성의 멤버를 호출합니다. 이 방법은 (대신 널의 코드와 같이) 나는 목표를 제공해야 속성의 인스턴스 방법이다

foreach (var p in this.GetType().GetProperties()) 
     { 
      //checking if it's a change request field 
      if (p.GetCustomAttributes(typeof(ChangeRequestFieldAttribute), false).Count() > 0) 
      { 

       MethodInfo method = p.PropertyType.GetMethod("SameValueAs"); 
       //problem here   
       var res = method.Invoke(null, new object[] { other.LastName }); 

      } 

     } 

경우 : 이것은 내가 지금까지있는 것입니다. 런타임에이 클래스 인스턴스의 특정 속성을 얻으려면 어떻게해야합니까?

+0

당신이 반사를 사용 왜 당신이 클래스에 대한 모든 것을 알고 있다면? 또는 자손의 일부 속성을 처리하고 싶습니까? –

+0

그것은 실제로 오류가 발생하기 쉬운 수동 속성 검사를 많이하지 않도록하는 데 사용, 플러스 개발자가이 속성에 속성을 추가 할 때 자동으로 위의 방법에 포함되고있다. – hoetz

답변

1

이미 PropertyInfo을 가지고 있기 때문에, 당신은 GetValue method를 호출 할 수 있습니다. 그래서 ...

MethodInfo method = p.PropertyType.GetMethod("SameValueAs"); 
//problem solved 
var propValue = p.GetValue(this); 

var res = method.Invoke(propValue, new object[] { other.LastName }); 
+0

D' oh, 고마워요! – hoetz

0

사용 PropertyInfo는 당신이 필요로하는 모든 속성의 값을 얻을 수 있습니다.

0

그냥 재산에서 가치를 얻고 평소처럼 사용하십시오.

foreach (var p in type.GetProperties()) 
{ 
     if (p.GetCustomAttributes(typeof(ChangeRequestFieldAttribute), false).Count() > 0) 
     { 

       //just get the value of the property & cast it. 
       var propertyValue = p.GetValue(<the instance>, null); 
       if (propertyValue !=null && propertyValue is ContactStringProperty) 
       { 
        var contactString = (ContactStringProperty)property; 
        contactString.SameValueAs(...); 
       } 
     } 
    } 
관련 문제