【发布时间】:2017-03-18 13:33:43
【问题描述】:
我找到了这个解决方案:
public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
var attrType = typeof(T);
var property = instance.GetType().GetProperty(propertyName);
return (T)property .GetCustomAttributes(attrType, false).First();
}
How to retrieve Data Annotations from codejgauffin 的代码
我总是这样使用扩展:
foo.GetAttributeFrom<StringLengthAttribute>(nameof(Foo.Bar)).MaximumLength
有没有办法通过使用像这样的 lambda 来传递 propertyName:
foo.GetAttributeFrom<StringLengthAttribute>(f => f.Bar).MaximumLength
提前谢谢你!
【问题讨论】:
标签: c# .net reflection lambda