1.类的构造函数有三种:实例构造函数,私有构造函数和静态构造函数,静态构造函数只能初始化静态数据,或执行一次特殊的操作,这种函数只执行一次,在第一次创建类的对象的时候或者调用静态成员时就会自动调用它,静态构造函数没有访问修饰符,也没有任何参数。
可以参考一下下面的代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 静态构造函数
{
class Program
{
static void Main(string[] args)
{
SayHello MyClass1 = new SayHello();
SayHello MyClass2 = new SayHello();
Console.ReadKey();
}
}
class SayHello
{
public SayHello()
{
Console.WriteLine("构造函数");
}
static SayHello()
{
Console.WriteLine("静态构造函数");
}
}
}
执行结果为:
静态构造函数
构造函数
构造函数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 静态构造函数
{
class Program
{
static void Main(string[] args)
{
SayHello.Name = "Tom";
Console.ReadKey();
}
}
class SayHello
{
public static string Name;
static SayHello()
{
Console.WriteLine("静态构造函数");
}
}
}
执行结果为:
静态构造函数