happyhippy

这个世界的问题在于聪明人充满疑惑,而傻子们坚信不疑。--罗素

思考一下下面三段这段程序的输出结果:

using System;
public class Type1
{
    
public static int i;
    
static Type1()//显式定义静态构造函数
    {
        Console.WriteLine(
"Explicit: In Type1 Class Constructor");
        i
=1;
    }

}


public class Type2
{
        
public static int i = Init(2);//由CSC编译器在编译时隐式创建静态构造函数
        public static int Init(int j)
        
{
        Console.WriteLine(
"Implicit: In Type2 Class Constructor");
        
return j;
        }

}


public class MainClass
{
    
static void Main()
    
{
        
//分别用下面三种情况下的Main函数,猜下输出结果:)
    }

}


1. 程序中有访问静态成员:

static void Main()
{
     Console.WriteLine(
"In Main Function");
     Console.WriteLine(Type1.i);
     Console.WriteLine(Type2.i);
}


2. 程序中没有访问静态成员,但有访问静态成员所声明的类中的实例成员:

static void Main()
{
     Console.WriteLine(
"In Main Function");
     Type1 t1 
= new Type1();
     Type2 t2 
= new Type2();
}


3.既不访问静态成员,也不访问实例成员

static void Main()
{
     Console.WriteLine(
"In Main Function");
}


    情况1下,输出编译和运行结果如下:

E:CSC>csc staticfield.cs
Microsoft (R) Visual C# 
2005 编译器 版本 8.00.50727.42
用于 Microsoft (R) Windows (R) 
2005 Framework 版本 2.0.50727
版权所有 (C) Microsoft Corporation 
2001-2005。保留所有权利。

E:CSC
>staticfield.exe
Implicit: In Type2 Class Constructor
In Main Function
Explicit: In Type1 Class Constructor
1
2

 

    情况2下,输出结果:

E:CSC>staticfield.exe
Implicit: In Type2 Class Constructor
In Main Function
Explicit: In Type1 Class Constructor

 


    情况3下,输出结果:

E:CSC>staticfield.exe
In Main Function

 

     是否跟我们想象中的结果不一样呢?^_^
    根据上面三个测试,我们可以得到如下结论(针对类中有定义静态字段的情况):

if(如果为类显式定义静态构造函数,例如上面的Type1)
{
    
if(程序中有访问该类的任意静态或实例成员)
    
{
         在进入Main函数之后,第一次访问该类中所定义的任何静态或实例成员之前,先调用静态构造函数;
         以后将不再调用该静态构造函数,同一个静态构造函数最多只调用一次!
    }

    
else
    
{
         程序中不调用该类的静态构造函数;
    }

else
{
    
if(程序中有访问该类的任意静态或实例成员)
    
{
         在执行Main函数中的代码之前,先调用静态构造函数;
         以后将不再调用该静态构造函数,同一个静态构造函数最多只调用一次!
    }

    
else
    
{
         程序中不调用该类的静态构造函数;
    }

}

     


posted on 2007-04-04 07:17  Silent Void  阅读(1165)  评论(2编辑  收藏  举报