讀取屬性更新和/或增強@Hans帕桑特我想答案將該屬性的檢索分離爲擴展方法。這已在方法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));
來源
2013-09-26 11:16:52
Seb
如果您只需檢查屬性的存在性,並且不從中檢索任何信息,那麼使用Attribute.IsDefined將消除一行代碼和醜陋的數組/鑄造。 – Aaronaught 2010-01-12 18:42:50