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(); } } 结果:I am Test 静态默认构造函数 i=1 I am Test 公有默认构造函数 i=1 |
如果静态默认构造函数和公有有参构造函数同时存在,我实例化类让它调用静态默认构造函数会怎么样呢?
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(); } } 结果:I am Test 静态默认构造函数 i=1 |
相关链接: