分享

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

 quasiceo 2012-12-05

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

 

     甚是奇怪,未得其解!


=======================================================================
野文(Jasson Qian)

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多