C# - 类_静态构造函数

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 /*------------------------------------------------------------------------------------------------------------
 7  * 类静态构造函数:
 8  *      1. 主要用于初始化类中的静态成员
 9  *      2. 不能使用任何访问修饰符
10  *      3. 必须是无参的
11  *      4. 不能直接调用
12  *      5. 仅执行一次
13 ------------------------------------------------------------------------------------------------------------*/
14 namespace 类_静态构造函数
15 {
16     class Person
17     {
18         // 字段
19         private static string _name;
20 
21         // 属性
22         public  static string Name
23         {
24             get { return _name; }
25         }
26 
27         // 静态构造函数, 不能使用任何访问修饰符, 仅执行一次
28         static Person()
29         {           
30             Console.WriteLine( "静态构造函数被调用了");
31             _name = "Hello, world!";
32         }
33 
34     }
35     class Program
36     {
37         static void Main(string[] args)
38         {     
39             Console.WriteLine(Person.Name);
40             Console.WriteLine(Person.Name);
41 
42            Console.ReadLine();
43         }
44     }
45 }

posted @ 2016-04-05 09:39  C/C++/Python/Java  阅读(216)  评论(0编辑  收藏  举报