c# - 通过 lambda 表达式传递属性名称以读取属性值

标签 c# .net reflection lambda

我找到了这个解决方案:

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/

相关文章:

.net - 这个图案叫什么?

c# - 从哈希表创建对象 C#

c# - Bot Framework : Enable PromptDialog. Cortana 说出的文本

c# - 鼠标悬停时的图像在页面加载时占用空间

c# - "try"应该在资源分配之前还是之后?

c# - 处理异常,这是一个好方法吗?

c# - Sharepoint 2010 从模板创建列表

c# - 哪种 C# 设计模式适合在 ASP.NET 中编写自定义工作流程

c# - 通过缓存或委托(delegate)调用提高性能?

c# - 查找类是否继承接口(interface)的更有效方法?