zoukankan      html  css  js  c++  java
  • 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

         甚是奇怪,未得其解!

  • 相关阅读:
    JDBC连接MySQL并且查询操作。
    struts
    KMP 剪花布条hdoj2087
    线段树---敌兵布阵hdoj 1166
    设计模式----观察者模式
    线段树--hdoj1754
    ZOJ 2283 Challenge of Wisdom
    SGU 134 Centroid
    UVA 1637 Double Patience
    HDU 4389 X mod f(x)
  • 原文地址:https://www.cnblogs.com/qguohog/p/2174457.html
Copyright © 2011-2022 走看看