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

时间:2011-01-14 08:50:50

标签: c# attributes

是否可以获取属性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
    }
}

1 个答案:

答案 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;
  }
}