每日一测2(关于构造函数)

1、一个类中可以有多个构造函数,包括无参的默认构造函数和有参的。

2、不加修饰符或显式的用private修饰的构造函数, 表示该类不能被实例化。

3、子类的构造函数,默认会调用父类的无参构造函数,如父类的无参构造函数不存在,会报错。 也可以显式的指定调用父类的哪个构造函数

 1     class Person
 2     {
 3         public int test;
 4         static Person()
 5         {
 6             Console.WriteLine("我是父类的静态构造函数");
 7         }
 8         public Person()
 9         {
10             test = 0;
11             Console.WriteLine("我是父类的默认构造函数 " + test.ToString());
12         }
13         public Person(int t)
14         {
15             test = t;
16             Console.WriteLine("我是父类的有参构造函数 " + test.ToString());
17         }
18     }
19 
20     class Chinese : Person
21     {
22         public Chinese() //默认会调用父类的默认构造函数,当父类没有默认构造函数则会报错(无法编译)
23         {
24             test++;
25             Console.WriteLine("我是子类的默认构造函数..." + test.ToString());
26         }
27 
28         public Chinese(int t)
29             : base(t) //调用指定父类的构造函数
30         {
31             test++;
32             Console.WriteLine("我是子类的有参构造函数..." + test.ToString());
33         }
34 
35         static Chinese()
36         {
37             Console.WriteLine("我是子类的静态构造函数...");
38         }
39     }
40 
41     class Program
42     {
43         static void Main(string[] args)
44         {
45             int t = 5;
46             Chinese cn = new Chinese(t);      
47             Console.ReadKey();
48         }
49     }

执行结果:

其他例子自己跑个测试。

4、私有构造函数一般用于静态类,不能被外部实例化,却可以在内部实例化, 区别于继承

 1     class Person
 2     {
 3         private Person(int t) //可有参可无参
 4         {
 5             Console.WriteLine("我是私有构造函数" + t.ToString());
 6         }
 7         public static Person CreatePerson(int at)
 8         {
 9             Person P = new Person(at);
10             return P;
11         }
12 
13     }
14 
15     //class Chinese : Person //不能被继承的,会报错
16     //{
17     //}
18     class Program
19     {
20         static void Main(string[] args)
21         {
22             int t = 5;
23             Person temp = Person.CreatePerson(t); //不能被外部实例化,可以在类内部实例化.    
24             Console.ReadKey();
25         }
26     }
原文地址:https://www.cnblogs.com/jolins/p/4118930.html