Retrieve custom attributes from an object

When I try to get custom attributes from object , the function returns null . Why?

 class Person { [ColumnName("first_name")] string FirstName { get; set; } Person() { FirstName = "not important"; var attrs = AttributeReader.Read(FirstName); } } static class AttributeReader { static object[] Read(object column) { return column.GetType().GetCustomAttributes(typeof(ColumnNameAttribute), false); } } 
+4
source share
1 answer

You pass this method string , "not important" . Therefore, Type typeof(string) . Which does not have these attributes . In addition, even Person does not have this attribute: only MemberInfo ( FirstName ) has them.

There are ways to do this by passing Expression :

 public static ColumnNameAttribute[] Read<T>(Expression<Func<T>> func) { var member = func.Body as MemberExpression; if(member == null) throw new ArgumentException( "Lambda must resolve to a member"); return (ColumnNameAttribute[])Attribute.GetCustomAttributes( member.Member, typeof(ColumnNameAttribute), false); } 

from

 var attrs = AttributeReader.Read(() => FirstName); 

However! I have to report that I'm not sure that the Person constructor is the right place for this. Caching is probably required.

If you do not want to use lambdas, then the transfer of Type and member-name will also work, i.e.

 var attrs = AttributeReader.Read(typeof(Person), "FirstName"); 

(and do reflection from there) - or mix with generics (for some reason):

 var attrs = Attribute.Read<Person>("FirstName"); 
+14
source

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


All Articles