Static变量在Debug和Release模式下的初始化顺序偶有差异

    新建一个简单的Console项目,包含三个class:

    image

   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模式下确实如此:

     image

     在Release模式下,若直接在Vs.net中按F5运行也是显示上图结果,但若按“Ctrl+F5”键运行或直接点击bin/release/StaticMember.exe”文件运行,则显示的是如下顺序:

    image

     甚是奇怪,未得其解!

原文地址:https://www.cnblogs.com/qguohog/p/2174457.html