静态和非静态

 

class ExampleTest
     {
        
static ExampleTest()
         {
             Console.WriteLine(
"test static default constructor in unstatic class");
         }

        
public ExampleTest()
         {
             Console.WriteLine(
"test default constructor in unstaic class");
         }
     }

    
static class ExampleTest2
     {
        
static ExampleTest2()
         {
             Console.WriteLine(
"test static Method in static class");
         }

        
#region 静态类不能调用实例构造函数

        
//public ExampleTest2()
        //{
        //     Console.WriteLine("test unstatic method in static class");
        //}

        
#endregion

        
#region 静态类中不能调用实例方法
        
//public void getAlert()
        //{
        //     Console.WriteLine("Alert,alert");
        //}
        #endregion

        
public static void getAlert()
         {
             Console.WriteLine(
"Alert,alert");
         }
     }


从上面两个类中,我们得到结论:
1
、构造函数,无论在静态类或非静态类中,如果我们定义了一个static的构造函数,那么只要创建这个类的实例或调用这个类的方法,都将自动调用这个Static的构造函数,并且Static的构造函数是不能有访问权限的。static的构造函数是不能有参数的。

2
、静态类中不能调用实例构造函数

2
、静态类中不能创建非静态的方法。即静态方法中只能创建静态方法,但在非静态类中可以调用静态方法(这个情况我们经常使用的)

____________________________________________________________________________________

静态构造函数:

1)用于对静态字段、只读字段等的初始化。              

2)添加static关键字,不能添加访问修饰符,因为静态构造函数都是私有的。        

3)类的静态构造函数在给定应用程序域中至多执行一次:只有创建类的实例或者引用类的任何静态成员才激发静态构造函数

4)静态构造函数是不可继承的,而且不能被直接调用。            

5)如果类中包含用来开始执行的 Main 方法,则该类的静态构造函数将在调用 Main 方法之前执行。    

6)任何带有初始值设定项的静态字段,则在执行该类的静态构造函数时,先要按照文本顺序执行那些初始值设定项。  

7)如果没有编写静态构造函数,而这时类中包含带有初始值设定的静态字段,那么编译器会自动生成默认的静态构造函数。

经典例子:

1 /**************************************************
2 *
3 * 1①②③……为执行顺序
4 * 2)输出结果: static A()
5 * static B()
6 * X = 1, Y = 2
7 ***************************************************/
8 using System;
9 class A
10 {
11 public static int X;
12
13 static A() // 执行完后返回到
14 {
15 X = B.Y + 1;
16 Console.WriteLine("static A()");
17 }
18 }
19
20 class B
21 {
22 public static int Y = A.X + 1; // 调用了A的静态成员,
23 // 转到A的静态构造函数---->
24
25 static B() // 如果带有初始值设定项的静态字段,
26 // 执行该类的静态构造函数时,
27 // 先要按照文本顺序执行那些初始值设定项。
28 // 转到初始值设定项---->
29 {
30 Console.WriteLine("static B()");
31 }
32
33 static void Main() // 程序入口,
34 // 如果类中包含用来开始执行的 Main 方法,
35 // 该类的静态构造函数将在调用 Main 方法之前执行。
36 // 转到B的静态构造函数---->
37 {
38 Console.WriteLine("X = {0}, Y = {1}", A.X, B.Y);// 输出结果
39 Console.ReadLine();
40 }
41 }

posted @ 2009-10-06 23:06  放羊的孩子  阅读(127)  评论(0)    收藏  举报