从对象获取属性
问题描述:
我想要获取某个对象属性的特定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;
}
}
你然后调用这样的:
var attr = someobject.GetMember(x => x.Height).GetAttribute<FooAttribute>();
但我想它在一个清洁步骤是这样的:
var attr = someobject.GetAttribute<FooAttribute>(x => x.Height);
我如何结合这两个功能来给这个签名?
更新:此外,为什么这不适用于枚举?
答
您将无法获得确切的签名。要使该方法起作用,它需要三个泛型类型参数(一个用于对象类型T
,一个用于属性类型TAttribute
,另一个用于属性类型TProperty
)。 T
和TProperty
可以根据使用情况推断,但需要指定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);
*不幸的是,一旦你指定一个泛型类型参数,你需要指定他们三个。*是的,这是我的经验,在编译器,我希望有另一种方式。尽管我更喜欢你的第二种形式,因为它不那么不必要的功能。 – 2014-10-17 13:23:50
虽然代码不能编译... – 2014-10-17 13:27:24
为什么这不适用于枚举? – 2014-10-18 07:27:22