1. public实例构造函数,protected实例构造函数,private实例构造函数,static构造函数有什么不同,请重点回答他们应该如何使用?
常见的构造函数修饰符大概有3种:public、protected、static。
public实例构造函数不用多说。
protected构造函数:该类可以继承,可以在被包内其他类中产生实例,但是无法在包外或者子类以外的地方产生实例。
static构造函数:静态构造函数,先于其他构造函数初始化。static声明的类不用实例化即可使用。
private实例构造函数:无法被继承,无法从外界获得一个对象,但是可以在类的内部产生一个实例。
这4种不同的实例构造函数应该如何使用呢?
public实例构造函数很简单,大多数的类声明构造函数都是public实例构造函数。如:
class Person { public Person() { } }
protected构造函数:
1: class Test
2: {
3: protected Test()
4: { Console.WriteLine("test create."); }
5: }
6:
7: class Test1 : Test
8: {
9: public Test1()
10: {
11: Console.WriteLine("test1 create.");
12: }
13: }
输出结果:
test create.
test1 create.
static构造函数:
1: class Test
2: {
3: protected Test()
4: { Console.WriteLine("test create."); }
5: static Test()
6: { Console.WriteLine("test static create."); }
7: }
8:
9: class Test1 : Test
10: {
11: public Test1()
12: {
13: Console.WriteLine("test1 create.");
14: }
15: }
输出结果:
test static create.
test create.
test1 create.
private构造函数:
1: class Test
2: {
3: private static Test t;
4: private static int i;
5: private Test()
6: { Console.WriteLine("test private create.i=" + i.ToString()); }
7: public static Test GetTest()
8: {
9: Console.WriteLine("i="+i.ToString());
10: if (t == null)
11: { t = new Test(); }
12: i++;
13: return t;
14: }
15: }
16:
17: class Test1
18: {
19: public Test1()
20: {
21: Test.GetTest();
22: Console.WriteLine("test1 create.");
23: Test.GetTest();
24: }
25: }
输出结果:
i=0
test private create.i=0
test1 create.
i=1