2011-03-30 6 views
4

사용자 지정 특성을 정의하고 코드를 읽는 코드가 있는데 작동하지 않습니다. 시도해보고 문제를 해결하기 위해 DisplayName을 사용하려고했지만 GetCustomAttribute 또는 GetCustomAttributes와 같은 문제가 여전히 발생하지 않았습니다. 아래 예가 있습니다.표시 이름과 같은 사용자 지정 특성이 GetCustomAttribute와 함께 표시되지 않습니다.

은 난 후 상기 클래스의 각 방법에 대한 displayName 특성을 나열하는 일부 코드가

class TestClass 
{ 
     public TestClass() { } 

     [DisplayName("this is a test")] 
     public long testmethod{ get; set; } 
} 

예를 들어 클래스에 설정된 displayName 특성을 ...있다.

TestClass testClass = new TestClass(); 

    Type type = testClass.GetType(); 

      foreach (MethodInfo mInfo in type.GetMethods()) 
      { 

      DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(mInfo, typeof(DisplayNameAttribute)); 

        if (attr !=null) 
        { 
         MessageBox.Show(attr.DisplayName); 

        } 


      } 

문제는 DisplayName 특성이 나열되지 않고 위의 코드가 컴파일되고 실행되며 메시지 상자를 표시하지 않는 것입니다.

각 루프마다 GetCustomAttributes를 사용하여 각 메서드의 모든 특성을 다시 나열하려고 시도했지만 심지어 DisplayName 특성이 나열되지는 않지만 컴파일 특성 및 기타 시스템 특성을 얻습니다.

누구나 내가 뭘 잘못하고 있는지 알 수 있습니까?

UPDATE- NerdFury가 메소드가 아니라 속성을 사용하고 있음을 지적 해 주신 것에 감사드립니다. 일단 모든 것이 바뀌었다.

답변

10

속성이 아닌 속성에 속성을 넣습니다. 다음 코드를 사용해보십시오.

TestClass testClass = new TestClass(); 

    Type type = testClass.GetType(); 

    foreach (PropertyInfo pInfo in type.GetProperties()) 
    { 
     DisplayNameAttribute attr = (DisplayNameAttribute)Attribute.GetCustomAttribute(pInfo, typeof(DisplayNameAttribute)); 

     if (attr !=null) 
     { 
      MessageBox.Show(attr.DisplayName); 
     } 
    } 
+1

+1. foreach 루프를'foreach (type.GetProperties())의 PropertyInfo pInfo '로 변경해야합니다. – KeithS

+0

나는 내가 그것을 놓쳤다라고 생각할 수있다!! , 많은 감사합니다. –

+1

@KeithS - 방금 알아 챘습니다. 감사. – NerdFury

관련 문제