2011-01-14 263 views
1

是否有可能獲得屬性獲取或設置屬性屬性沒有StackFrame如何獲得屬性獲取或設置屬性屬性

例如

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

您可以隨時使用`this.GetType()。GetProperty(「SomeProp」)。Attributes [「AttrName」]` - 但我想你不想硬編碼屬性名稱! – VinayC 2011-01-14 09:00:01

回答

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