2012-05-31 6 views
2

안녕하세요, 클래스의 속성 이름에 해당 속성에 대한 사용자 지정 속성 값이 있으면 어떻게 가져올 수 있습니까? 및 물론 사용자 정의 속성 이름.속성 값으로 속성 이름 가져 오기

+2

을 더 설명해주십시오, 당신을 질문은있는 그대로 명확하지 않으며 닫힐 가능성이 높습니다. –

답변

0

사용자 정의 속성으로 속성 이름을 가져옵니다 :

public static string[] GetPropertyNameByCustomAttribute 
     <ClassToAnalyse, AttributeTypeToFind> 
     (
     Func<AttributeTypeToFind, bool> attributePredicate 
    ) 
     where AttributeTypeToFind : Attribute 
    { 
     if (attributePredicate == null) 
     { 
     throw new ArgumentNullException("attributePredicate"); 
     } 
     else 
     { 
     List<string> propertyNames = new List<string>(); 

     foreach 
     (
      PropertyInfo propertyInfo in typeof(ClassToAnalyse).GetProperties() 
     ) 
     { 
      if 
      (
      propertyInfo.GetCustomAttributes 
      (
       typeof(AttributeTypeToFind), true 
      ).Any 
      (
       currentAttribute =>     
       attributePredicate((AttributeTypeToFind)currentAttribute) 
      ) 
     ) 
      { 
      propertyNames.Add(propertyInfo.Name); 
      } 
     } 

     return propertyNames.ToArray(); 
     } 
    } 

시험 설비 :

public class FooAttribute : Attribute 
{ 
    public String Description { get; set; } 
} 

class FooClass 
{ 
    private int fooProperty = 42; 

    [Foo(Description="Foo attribute description")] 
    public int FooProperty 
    { 
    get 
    { 
     return this.fooProperty; 
    } 
    } 

} 

테스트 케이스 :

// It will return "FooProperty" 
GetPropertyNameByCustomAttribute<FooClass, FooAttribute> 
( 
    attribute => attribute.Description == "Foo attribute description" 
); 


// It will return an empty array 
GetPropertyNameByCustomAttribute<FooClass, FooAttribute> 
( 
    attribute => attribute.Description == "Bar attribute description" 
); 
+0

이것은 속성과 어떤 관련이 있습니까? 의심의 여지가 없지만 대답에는 "속성"이라는 단어가 없습니다. – aquinas

+0

왜 이것이 downvoted되고 있는지 잘 모르겠다. 내 질문에 대한 질문에 OP는 주어진 개체에 대한 invokable 속성 목록을 검색하는 방법에 대한 질문입니다. 이 대답에 대한 질문에 정보 부족을 고려하면 옳은 것 같습니다. –

+0

Reflection API에 대해 들었던 다른 관련 질문으로 인해 Reflection API를 사용하는 방법을 알고 싶어한다는 것을 분명히 이해했습니다.이 API를 모르는 사람은 자신의 의도를 설명하기가 매우 어렵습니다. – fsenart