构造函数
从基类开始构造对象。
public class MyBaseClass
{
public MyBaseClass()
{
Console.WriteLine("In MyBaseClass()");
}
public MyBaseClass(int i)
{
Console.WriteLine("In MyBaseClass(int i)");
}
}
public class MyDerivedClass : MyBaseClass
{
public MyDerivedClass()
{
Console.WriteLine("In MyDerivedClass()");
}
public MyDerivedClass(int i)
{
Console.WriteLine("In MyDerivedClass(int i)");
}
//public MyDerivedClass(int i, int j)
//{
// Console.WriteLine("In MyDerivedClass(int i,int j)");
//}
public MyDerivedClass(int i, int j)
: base(i)
{
Console.WriteLine("In MyDerivedClass(int i,int j):base(i)");
}
}
class Program
{
static void Main(string[] args)
{
//Event1
MyDerivedClass myObj1 = new MyDerivedClass();
Console.WriteLine();
//Event2
MyDerivedClass myObj2 = new MyDerivedClass(4);
Console.WriteLine();
//Event3
MyDerivedClass myObj3 = new MyDerivedClass(4,8);
Console.WriteLine();
Console.ReadKey();
}
}
程序输出:
In MyBaseClass()
In MyDerivedClass()
In MyBaseClass()
In MyDerivedClass(int i)
In MyBaseClass(int i)
In MyDerivedClass(int i,int j):base(i)
很明显,只有在用base显示调用父类的构造函数时,程序才不会默认的调用不带参数的构造函数。