Custom attributes such as Displayname not listed in GetCustomAttribute

I have code to define custom attributes, and then to read in the code, it does not work. To try and fix the problem, I came back and tried to use DisplayName, however I still have the same problem as GetCustomAttribute, or GetCustomAttributes does not list them. I have an example below.

I have a DisplayName attribute set in a class, for example ...

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

Then I have code to display the DisplayName attribute for each method in the class above.

 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 in the list; over compilation of the code, no messages are executed and are not displayed.

I even tried to use a for each loop with GetCustomAttributes, listing all the attributes for each method again, the DisplayName attribute is never displayed, however I get compilation attributes and other such system attributes.

Does anyone know what I'm doing wrong?

UPDATE. Many thanks to NerdFury for pointing out that I used methods, not properties. Once upon a time everything changed.

+4
source share
1 answer

You put an attribute in a Property, 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); } } 
+10
source

Source: https://habr.com/ru/post/1345918/


All Articles