[英]Custom Attributes such as Displayname not listed with GetCustomAttribute
I have some code to define custom attributes and then to read in the code, it fails to work. 我有一些代码来定义自定义属性然后读入代码,它无法工作。 To try and fix the problem I have gone back and tried to use DisplayName, however , I am still having the same issue GetCustomAttribute or GetCustomAttributes fails to list them. 为了尝试解决问题我已经回去并尝试使用DisplayName,但是,我仍然遇到相同的问题GetCustomAttribute或GetCustomAttributes无法列出它们。 I have an example below. 我有一个例子如下。
I have a DisplayName Attribute set in a class, for example... 我在类中设置了DisplayName属性,例如......
class TestClass
{
public TestClass() { }
[DisplayName("this is a test")]
public long testmethod{ get; set; }
}
I then have some code to list the DisplayName Attribute for each method in the class above. 然后我有一些代码列出上面类中每个方法的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);
}
}
The problem is that there are no DisplayName Attributes listed, Above code compiles, runs and doesn't display any messageboxes. 问题是没有列出DisplayName属性,上面的代码编译,运行并且不显示任何消息框。
I have even tried to use a for each loop with GetCustomAttributes, listing all the attributes for each method again the DisplayName Attribute is never listed, however, I do get the compilation attributes and other such system attributes. 我甚至尝试使用GetCustomAttributes的每个循环,再次列出每个方法的所有属性,从未列出DisplayName属性,但是,我确实获得了编译属性和其他此类系统属性。
Anyone have any idea what I am doing wrong? 任何人都知道我做错了什么?
UPDATE- Many thanks to NerdFury for pointing out that I was using Methods and not Properties. 更新 - 非常感谢NerdFury指出我使用的是Method而不是Properties。 Once changed every thing worked. 一旦改变,每件事都有效。
You are putting the attribute on a Property and not a Method. 您将属性放在属性而不是方法上。 Try the following code: 请尝试以下代码:
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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.