我找到了这个解决方案:
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();
}
由 jgauffin 编写的代码,来自 How to retrieve Data Annotations from code
我总是这样使用扩展:
foo.GetAttributeFrom<StringLengthAttribute>(nameof(Foo.Bar)).MaximumLength
有没有办法使用 lambda 来传递 propertyName,例如:
foo.GetAttributeFrom<StringLengthAttribute>(f => f.Bar).MaximumLength
提前谢谢您!
最佳答案
您可以将工作拆分为两个函数,以绕过为泛型方法指定所有泛型参数类型限制
public static object[] GetPropertyAttributes<TObject, TProperty>(
this TObject instance,
Expression<Func<TObject, TProperty>> propertySelector)
{
//consider handling exceptions and corner cases
var propertyName = ((PropertyInfo)((MemberExpression)propertySelector.Body).Member).Name;
var property = instance.GetType().GetProperty(propertyName);
return property.GetCustomAttributes(false);
}
public static T GetFirst<T>(this object[] input) where T : Attribute
{
//consider handling exceptions and corner cases
return input.OfType<T>().First();
}
然后像这样使用它
foo.GetPropertyAttributes(f => f.Bar)
.GetFirst<StringLengthAttribute>()
.MaximumLength;
关于c# - 通过 lambda 表达式传递属性名称以读取属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42875027/