是否可以获取属性get属性或设置body 而不使用StackFrame
?
例如
[SomeAttribute]
public int SomeProp
{
get
{
//Get of SomeAttribute is set on this property
}
set
{
//Get of SomeAttribute is set on this property
}
}
答案 0 :(得分:1)
您可以编写这样的函数,并通过表达式而非字符串lliterals
获取属性名称public string Item(this T obj, Expression<Func<T, object>> expression)
{
if (expression.Body is MemberExpression)
{
return ((MemberExpression)expression.Body).Member.Name;
}
if (expression.Body is UnaryExpression)
{
return ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member.Name;
}
throw new InvalidOperationException();
}
用法:
public int SomeProp
{
get
{
var attribs =
this.GetType().GetProperty(this.Item(o => o.SomeProp)).Attributes;
}
}