4

カスタム属性を定義してコードを読み込むコードがいくつかありますが、機能しません。問題を解決するために、戻って DisplayName を使用しようとしましたが、同じ問題 GetCustomAttribute または GetCustomAttributes がそれらを一覧表示できないという問題がまだあります。以下に例を示します。

たとえば、クラスに 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 で for each ループを使用しようとしましたが、各メソッドのすべての属性を再度リストしましたが、DisplayName 属性はリストされませんが、コンパイル属性やその他のシステム属性を取得します。

誰が私が間違っているのか知っていますか?

更新 - プロパティではなくメソッドを使用していたことを指摘してくれた NerdFury に感謝します。一度変更すると、すべてが機能しました。

4

1 に答える 1

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);   
       }
   }
于 2011-03-30T17:22:51.330 に答える