繁体   English   中英

从对象获取属性

[英]Get Attribute from object

我希望得到一个特定的Attribute一个对象的属性之一。

我使用此代码作为入门

public static class ObjectExtensions {
  public static MemberInfo GetMember<T,R>(this T instance, 
    Expression<Func<T, R>> selector) {
      var member = selector.Body as MemberExpression;
      if (member != null) {
        return member.Member;
      }
      return null;
  }

public static T GetAttribute<T>(this MemberInfo meminfo) where T : Attribute {
  return meminfo.GetCustomAttributes(typeof(T)).FirstOrDefault() as T;
  }
}

然后您这样称呼它:

var attr = someobject.GetMember(x => x.Height).GetAttribute<FooAttribute>();

但我希望像这样干净的一步:

var attr = someobject.GetAttribute<FooAttribute>(x => x.Height);

我如何结合这两个功能来赋予此签名?

更新:另外,为什么这对于枚举不起作用?

您将无法获得确切的签名。 为了使该方法起作用,它需要三个泛型类型参数(一个用于对象类型T ,一个用于属性类型TAttribute ,一个用于属性类型TProperty )。 可以从用法中推断出TTProperty ,但是需要指定TAttribute 不幸的是,一旦指定了一个泛型类型参数,就需要同时指定所有三个参数。

public static class ObjectExtensions {
    public static TAttribute GetAttribute<T, TAttribute, TProperty> (this T instance, 
        Expression<Func<T, TProperty>> selector) where TAttribute : Attribute {
        var member = selector.Body as MemberExpression;
        if (member != null) {
            return member.Member.GetCustomAttributes(typeof(TAttribute)).FirstOrDefault() as TAttribute;
        }
        return null;
    }
}   

这就是为什么问题中的两种方法要分开开始的原因。 写起来比较容易

var attr = someobject.GetMember(x => x.Height).GetAttribute<FooAttribute>();

比写

var attr = someobject.GetAttribute<Foo, FooAttribute, FooProperty>(x => x.Height);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM