0%

查缺补漏-CSharp

记录搬砖过程中遇到的疑问

构造函数

子类构造函数始终默认调用父类无参构造函数

若父类没有无参构造函数时,子类应显式调用父类有参构造函数,否则编译不过

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
TestFunc();
}
static void TestFunc()
{
Child c = new Child("22");
}
}
class BassTest
{
//public BassTest()
//{Console.WriteLine("BassNoneParam");}
public BassTest(string s) : this(s,"333")
{Console.WriteLine("BassOneParam" + s);}
public BassTest(string s, string t)
{Console.WriteLine("BassTwoParam" + s + t);}
}
class Child : BassTest
{
//public Child()
//{Console.WriteLine("ChildNoneParam");}
public Child(string s) : this(s,"111")
{Console.WriteLine("ChildOneParam" + s);}
public Child(string s, string t):base(s)
{Console.WriteLine("ChildTwoParam" + s + t);}
}

示例中:this()调用子类中对应参数的构造函数
base()调用父类中对应参数的构造函数
Child c = new Child("22");输出为:

BassTwoParam22333
BassOneParam22
ChildTwoParam22111
ChildOneParam22