如何在属性get或set body中获取属性的属性

是否可以在没有StackFrame情况下获取属性get或set body中的属性?

例如

 [SomeAttribute] public int SomeProp { get { //Get of SomeAttribute is set on this property } set { //Get of SomeAttribute is set on this property } } 

您可以编写这样的函数,并通过表达式而不是字符串lliterals获取属性名称

 public string Item(this T obj, Expression> 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; } }