关于静态构造函数

关于静态构造函数一直有些不特别明白,现在上一次实例,仅供参考。

代码

 1     public class TestStaticConstructor
 2     {
 3         public static int intTemp = 0;
 4 
 5         //public static TestStaticConstructor()
 6         static TestStaticConstructor()  // Cannot use access modifier in static constructor
 7         {
 8             Console.WriteLine("static:" + TestStaticConstructor.intTemp.ToString());
 9             intTemp++;
10         }
11 
12         public TestStaticConstructor()
13         {
14             Console.WriteLine("non-static:" + TestStaticConstructor.intTemp.ToString());
15             intTemp++;
16         }
17     }
下面是测试代码

第一种情况:只声明

代码
        static void Main(string[] args)
        {
            
// change this line next
            TestStaticConstructor tc; 
            // same as code behind
            //TestStaticConstructor tc = null;

            Console.WriteLine(
"Current:" + TestStaticConstructor.intTemp.ToString());
            Console.Read();
        }

  输出:

static:0
Current:1
 第二种情况:声明一次
            TestStaticConstructor tc = new TestStaticConstructor();
            Console.WriteLine(
"Current:" + TestStaticConstructor.intTemp.ToString());

            Console.Read();

 输出:

static:0
non-static:1
Current:2

 第三种情况:声明两次

代码
            TestStaticConstructor tc = new TestStaticConstructor();
            TestStaticConstructor tc1 
= new TestStaticConstructor();
            Console.WriteLine(
"Current:" + TestStaticConstructor.intTemp.ToString());

  

输出:

static:0
non-static:1
non-static:2
Current:3

Title
MSDN相关解释:
静态构造函数用于初始化任何静态数据,或用于执行仅需执行一次的特定操作。在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数
 

静态构造函数具有以下特点:

  • 静态构造函数既没有访问修饰符,也没有参数。

  • 在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化

  • 无法直接调用静态构造函数。

  • 在程序中,用户无法控制何时执行静态构造函数。

  • 静态构造函数的典型用途是:当类使用日志文件时,将使用这种构造函数向日志文件中写入项。

  • 静态构造函数在为非托管代码创建包装类时也很有用,此时该构造函数可以调用 LoadLibrary 方法。

     引用: http://msdn.microsoft.com/zh-cn/library/k9x6w0hc(VS.80).aspx

  

原文地址:https://www.cnblogs.com/tukzer/p/1681897.html