要更新和/或增强@Hans Passant的答案,我会将属性的检索分为扩展方法。这具有在方法GetProperty()中删除讨厌的魔术字符串的附加好处。
public static class PropertyHelper<T>
{
public static PropertyInfo GetProperty<TValue>(
Expression<Func<T, TValue>> selector)
{
Expression body = selector;
if (body is LambdaExpression)
{
body = ((LambdaExpression)body).Body;
}
switch (body.NodeType)
{
case ExpressionType.MemberAccess:
return (PropertyInfo)((MemberExpression)body).Member;
default:
throw new InvalidOperationException();
}
}
}
然后您的测试减少到两行
var property = PropertyHelper<MyClass>.GetProperty(x => x.MyProperty);
Attribute.IsDefined(property, typeof(MyPropertyAttribute));
Attribute.IsDefined
可以消除一行代码和丑陋的数组/广播。