[英]Get Attribute from object
I want to get a specific Attribute
on one of an object's properties. 我希望得到一个特定的
Attribute
一个对象的属性之一。
I used this code as a starter : 我使用此代码作为入门 :
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;
}
}
Which you then call like this: 然后您这样称呼它:
var attr = someobject.GetMember(x => x.Height).GetAttribute<FooAttribute>();
But I'd like it in one clean step like this: 但我希望像这样干净的一步:
var attr = someobject.GetAttribute<FooAttribute>(x => x.Height);
How do I combine those two functions to give this signature? 我如何结合这两个功能来赋予此签名?
Update: Also, why does this not work for enums? 更新:另外,为什么这对于枚举不起作用?
You won't be able to get that exact signature. 您将无法获得确切的签名。 For the method to work, it needs three generic type arguments (one for the object type
T
, one for the attribute type TAttribute
, and one for the property type TProperty
). 为了使该方法起作用,它需要三个泛型类型参数(一个用于对象类型
T
,一个用于属性类型TAttribute
,一个用于属性类型TProperty
)。 T
and TProperty
can be inferred from usage, but TAttribute
needs to be specified. 可以从用法中推断出
T
和TProperty
,但是需要指定TAttribute
。 Unfortunately, once you specify one generic type argument, you need to specify all three of them. 不幸的是,一旦指定了一个泛型类型参数,就需要同时指定所有三个参数。
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;
}
}
This is why the two methods in the question were separate to begin with. 这就是为什么问题中的两种方法要分开开始的原因。 It's easier to write
写起来比较容易
var attr = someobject.GetMember(x => x.Height).GetAttribute<FooAttribute>();
than to write 比写
var attr = someobject.GetAttribute<Foo, FooAttribute, FooProperty>(x => x.Height);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.