天天看點

Static變量在Debug和Release模式下的初始化順序偶有差異

建立一個簡單的Console項目,包含三個class:

Static變量在Debug和Release模式下的初始化順序偶有差異

   Helper.cs是一個工具類,提供一些靜态的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticMember
{
    class Helper
    {
        internal static string GetVersion()
        {
            Console.WriteLine("Step 2.<Helper.GetVersion> The methods GetVersion() had been invoked. It indicates that Tester.version had been initilized.");
            return "V1.0.0.2566";
        }
    }
}


           
    Tester.cs是一個含有靜态變量的類:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticMember
{
    class Tester
    {
        static string version = Helper.GetVersion();

        internal static void Init()
        {
            Console.WriteLine("Tester.Init()");
        }
    }
}
           

     Program.cs中的Main函數初始化Tester類的一個執行個體。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StaticMember
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine( "Step 1. <Program.Main> Before create an instance of Tester class. ");
            Tester tester = new Tester();

            //Tester.Init();

            Console.Read();
        }
    }
}
           

     按一般邏輯,應該是先顯示Step1….., 然後再顯示Step 2….。在Dubug模式下确實如此:

Static變量在Debug和Release模式下的初始化順序偶有差異

     在Release模式下,若直接在Vs.net中按F5運作也是顯示上圖結果,但若按“Ctrl+F5”鍵運作或直接點選“bin/release/StaticMember.exe”檔案運作,則顯示的是如下順序:

Static變量在Debug和Release模式下的初始化順序偶有差異

     甚是奇怪,未得其解!

繼續閱讀