2013年7月19日 星期五

Static Constructor vs Constructor 靜態建構式

參考:MSDN 靜態建構式
靜態建構函式可以用來初始化任何靜態資料,或執行只需執行一次的特定動作。
在建立第一個執行個體或參考任何靜態成員之前,會自動呼叫靜態建構函式。

C# Code
class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("了解Static Constructor 與Constructor");
            ForTestConstractor x = new ForTestConstractor();
            Console.ReadLine();
        }
     }

class ForTestConstractor
    {
         //static Constrator
        static ForTestConstractor()
        {
            Console.WriteLine("static Constructor");
        }
        public ForTestConstractor()
        {
            Console.WriteLine("normal Constructor");
        }
    }
執行結果:

了解Static Constructor 與Constructor
static Constructor
normal Constructor