C#静态构造函数
静态构造函数
静态构造函数用来初始化静态变量,这个构造函数是属于类的,而不是属于哪个实例的。
就是说这个构造函数只会被执行一次。也就是在创建第一个实例或引用任何静态成员之前,由.NET自动调用。
public class Test
{
static int i;
static Test()
{
i = 1;
Console.WriteLine("I am Test 默认构造函数 i={0}", i);
}
}
public class ProgramTest
{
static void Main(string[] args)
{
Test t1 = new Test();
Console.Read();
}
}
静态构造函数的特点:
1.静态构造函数既没有访问修饰符,也没有参数。
2.在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化类,也就是无法直接调用静态构造函数,也无法控制什么时候执行静态
构造函数。
3.一个类只能有一个静态构造函数,最多只能运行一次。
4.静态构造函数不可以被继承。
5.如果没有静态构造函数,而类中的静态成员有初始值,那么编译器会自动生成默认的静态构造函数。
如果静态默认构造函数和公有默认构造函数同时存在,会怎么样呢?
public class Test
{
static int i;
static Test()
{
i = 1;
Console.WriteLine("I am Test 静态默认构造函数 i={0}", i);
}
public Test()
{
Console.WriteLine("I am Test 公有默认构造函数 i={0}", i);
}
}
public class ProgramTest
{
static void Main(string[] args)
{
Test t1 = new Test();
Console.Read();
}
}
如果静态默认构造函数和公有有参构造函数同时存在,我实例化类让它调用静态默认构造函数会怎么样呢?
public class Test
{
static int i;
static Test()
{
i = 1;
Console.WriteLine("I am Test 静态默认构造函数 i={0}", i);
}
public Test(int j)
{
Console.WriteLine("I am Test 公有有参构造函数 i={0}", j);
}
}
public class ProgramTest
{
static void Main(string[] args)
{
Test t1 = new Test(); //系统会提示错误
Console.Read();
}
}
如果静态默认构造函数和公有有参构造函数同时存在,我实例化类让它调用公有构造函数会怎么样呢?
public class Test
{
static int i;
static Test()
{
i = 1;
Console.WriteLine("I am Test 静态默认构造函数 i={0}", i);
}
public Test(int j)
{
Console.WriteLine("I am Test 公有有参构造函数 i={0}", j);
}
}
public class ProgramTest
{
static void Main(string[] args)
{
Test t1 = new Test(2);
Console.Read();
}
}