2013-06-26 78 views
0

我有這個簡單的程序,問題是代碼永遠達不到TestClassAttribute類。控制檯輸出爲:屬性類別不工作

init 
executed 
end 

守則

class Program 
{ 
    static void Main(string[] args) 
    { 
     Console.WriteLine("init"); 
     var test = new Test(); 
     test.foo(); 
     Console.WriteLine("end"); 
     Console.ReadKey(); 
    } 
    public class TestClassAttribute : Attribute 
    { 
     public TestClassAttribute() 
     { 
      Console.WriteLine("AttrClass"); 
      Console.WriteLine("I am here. I'm the attribute constructor!"); 
      Console.ReadLine(); 
     } 
    } 

    public class Test 
    { 
     [TestClass] 
     public void foo() 
     { 
      Console.WriteLine("executed"); 
     } 
    } 
} 
+3

您從不構建「TestClassAttribute」的實例,例如,與'新的TestClassAttribute()'。 –

回答

3

你或許應該在How do attribute classes work?閱讀起來。

當您創建應用於它們的對象時,它們不會被實例化,而不是一個靜態實例,而不是每個對象實例1。他們也不會訪問它們應用到的類。

您可以嘗試獲取類,方法,屬性等的屬性列表。當您獲取這些屬性的列表時 - 這是他們將被實例化。然後您可以對這些屬性中的數據採取行動。

2

屬性不會自己做任何事情。他們甚至沒有在之前構建,要求在特定類別/方法上的屬性。

因此,要讓您的代碼編寫「AttrClass」,您需要明確要求foo方法的屬性。

0

不,不。屬性是特殊。直到您使用反射才能找到它們,它們的構造函數纔會運行。他們不需要需要然後運行。例如,這個小方法反映到屬性:

public static string RunAttributeConstructor<TType>(TType value) 
{ 
    Type type = value.GetType(); 
    var attributes = type.GetCustomAttributes(typeof(TestClassAttribute), false); 
} 

你會看到,無論你把這個在您的Main該屬性將運行構造函數。

1

屬性被懶惰地實例化。你必須得到屬性才能調用構造函數。

var attr = test.GetType().GetMethod("foo") 
      .GetCustomAttributes(typeof(TestClassAttribute), false) 
      .FirstOrDefault();