2010-01-21 26 views

回答

2

我不確定這是否是一般情況,但我是這麼認爲的。請嘗試以下操作:

class Program 
{ 
    static void Main(string[] args) 
    { 
     // display the custom attributes on our method 
     Type t = typeof(Program); 
     foreach (object obj in t.GetMethod("Method").GetCustomAttributes(false)) 
     { 
      Console.WriteLine(obj.GetType().ToString()); 
     } 

     // display the custom attributes on our delegate 
     Action d = new Action(Method); 
     foreach (object obj in d.Method.GetCustomAttributes(false)) 
     { 
      Console.WriteLine(obj.GetType().ToString()); 
     } 

    } 

    [CustomAttr] 
    public static void Method() 
    { 
    } 
} 

public class CustomAttrAttribute : Attribute 
{ 
} 
+0

感謝您的快速響應 – djp

3

使用委託的Method屬性的GetCustomAttributes方法。下面是一個示例:

delegate void Del(); 

    [STAThread] 
    static void Main() 
    { 
     Del d = new Del(TestMethod); 
     var v = d.Method.GetCustomAttributes(typeof(ObsoleteAttribute), false); 
     bool hasAttribute = v.Length > 0; 
    } 

    [Obsolete] 
    public static void TestMethod() 
    { 
    } 

如果該方法具有屬性,var v將包含它;否則它將是一個空數組。

+0

感謝您的快速響應 – djp