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");
source share