2011-05-25 31 views
1

是否可以從應用它的項目(例如方法)中訪問屬性的屬性?例如,使用下面的代碼,我可以使用「Search」方法訪問「RequiresConnection」屬性的屬性嗎?從其目標(例如方法)中訪問.Net屬性的屬性

[RequiresConnection] 
    public SearchResult Search(SearchInfo searchInfo) 
    { 
    } 

回答

3

當然

class TheClass { 
    [RequiresConnection] 
    public SearchResult Search(SearchInfo searchInfo) { 
    MethodInfo methodInfo = typeof(TheClass).GetMethod("Search"); 
    RequiresConnection attrib = (RequiresConnection).methodInfo.GetCustomAttributes(
     typeof(RequiresConnection), 
     false)[0]; 
0

您可以使用Reflection。這個例子並不是專門做你想要的,但你可以通過在你的方法中調用GetCustomAttributes來適應它。

0

肯定。這將是沿着

var attributes = StackTrace.GetFrame(0).GetMethod().GetCustomAttributes();