【问题标题】:Custom Attributes such as Displayname not listed with GetCustomAttribute自定义属性(例如显示名称)未与 GetCustomAttribute 一起列出
【发布时间】:2011-03-30 17:21:30
【问题描述】:

我有一些代码来定义自定义属性,然后读入代码,它无法工作。为了尝试解决问题,我返回并尝试使用 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 指出我使用的是方法而不是属性。更改后一切正常。

【问题讨论】:

    标签: c# reflection attributes getcustomattributes


    【解决方案1】:

    您将属性放在属性而不是方法上。试试下面的代码:

    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。您应该将 foreach 循环更改为 foreach (PropertyInfo pInfo in type.GetProperties())
    • @KeithS - 我自己也注意到了。谢谢。
    • Aways 我得到 attr null
    猜你喜欢
    • 2021-08-15
    • 2011-07-11
    • 1970-01-01
    • 2016-07-26
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2014-06-16
    • 1970-01-01
    相关资源
    最近更新 更多