因为前面的一篇的文章已介绍了静态构造函数的一些特性,这篇文章着重介绍静态构造函数的一些用法:
代码如下:
//代码段一
using System;
class MyClass
{
public static int x;
public static int y;
static MyClass ()
{
x = 100;
y = 200;
}
static void Main()
{
Console.WriteLine("{0},{1}",MyClass.x,MyClass.y);//在C#中静态成员属于类的成员,不//需要实例化对象来调用。
}
}
运行结果:100,200
//代码段二
class Test
{
private static int id = 5;
public static int Id
{
get
{
return id;
}
}
}
class Test1
{
private static int id;
static Test1()
{
if (Test.Id < 10)
{
id = 20;
}
else
{
id = 10;
}
Console.WriteLine("Static Constructor for Class Test1 called.");
}
public static void print()
{
Console.WriteLine("Test1.id=" + Test1.id);
}
static void Main(string[] args)
{
Test1.print();
}
}
运行结果:
Static Constructor for Class Test1 Called.
Test1.id = 20
结论:代码段二,在类Test1中静态成员不是一开始就初始化,而是在静态构造函数根据有条件地进行初始化。
评论