C# 语法练习(11): 类[三] - 构造函数、析构函数、base、this
2009-02-23 08:16:51 来源:WEB开发网自动调用父类的构造方法:
using System;
class Parent
{
public Parent() { Console.WriteLine("Parent"); }
}
class Child1 : Parent
{
public Child1() { Console.WriteLine("Child1"); }
public Child1(int x) { Console.WriteLine(x); }
}
class Child2 : Child1
{
public Child2() { Console.WriteLine("Child2"); }
public Child2(int x, int y) { Console.WriteLine(x + y); }
}
class Program
{
static void Main()
{
Parent p = new Parent(); // Parent
Child1 c1 = new Child1(); // Parent / Child1
Child2 c2 = new Child2(); // Parent / Child1 / Child2
Child1 c11 = new Child1(999); // Parent / 999
Child2 c22 = new Child2(111, 222); // Parent / Child1 / 333
Console.ReadKey();
}
}
base:
using System;
class Parent
{
public Parent() { Console.WriteLine("Parent"); }
public Parent(int x, int y) { Console.WriteLine(x + y); }
public Parent(string s1, string s2) { Console.WriteLine(s1 + s2); }
}
class Child1 : Parent
{
public Child1() { Console.WriteLine("Child1"); }
}
class Child2 : Parent
{
public Child2() : base() { Console.WriteLine("Child2"); }
}
class Child3 : Parent
{
public Child3() : base(111,222) { Console.WriteLine("Child3"); }
}
class Child4 : Parent
{
public Child4() : base("111", "222") { Console.WriteLine("Child4"); }
}
class Program
{
static void Main()
{
Child1 c1 = new Child1(); // Parent / Child1
Child2 c2 = new Child2(); // Parent / Child2
Child3 c3 = new Child3(); // 333 / Child3
Child4 c4 = new Child4(); // 111222 / Child4
Console.ReadKey();
}
}
更多精彩
赞助商链接