Appearance
继承
继承,是类与类的关系,想表达的是某个类与某个类在属性上、功能上的复用关系。
当一个类继承了另一个类的时候,被继承的叫做子类,继承的叫做父类。
B继承A,B是子类(也叫派生类),A是父类(也叫基类)。
单继承
单继承,指子类只有一个父类的继承。
csharp
class A
{
public void SayHello()
{
Console.WriteLine("Hello!");
}
}
class B : A // 使用冒号表示继承关系
{
public void SayWorld()
{
Console.WriteLine("World!");
}
}
public class App
{
static void Main(string[] args)
{
B _b = new B();
_b.SayHello();
_b.SayWorld();
Console.ReadKey();
}
}
上例可以看到,虽然我们只实例化了B类,但是由于B继承了A,所以B也能使用A的方法。
多继承
多继承,即子类有多个父类。
C#不支持多重继承,但是允许通过接口来完成多重继承。
csharp
class A
{
public void SayHello()
{
Console.WriteLine("Hello!");
}
}
class B : A, C
{
public void SayWorld()
{
Console.WriteLine("World!");
}
public void SayYeah()
{
Console.WriteLine("Yeah!");
}
}
public interface C
{
void SayYeah();
}
public class App
{
static void Main(string[] args)
{
B _b = new B();
_b.SayHello();
_b.SayWorld();
_b.SayYeah();
Console.ReadKey();
}
}
继承中的构造函数
先调父,后调子
csharp
class A
{
public A()
{
Console.WriteLine("父构造");
}
}
class B : A
{
public B() { Console.WriteLine("子构造"); }
}
public class App
{
static void Main(string[] args)
{
B b = new B();
Console.ReadKey();
}
}
实例化需注意
父类声明的变量可以以子类实例化。但是,由于声明的是父类,所以即便实例化的是子类,也只能够访问到继承来的父类的方法。
这其实有点过滤器的味道。可以通过这种方式,知道子类的父类都有什么方法,同时又排除掉子类自己的方法
csharp
class A
{
public void SayHello()
{
Console.WriteLine("Hello!");
}
}
class B : A
{
public void SayWorld()
{
Console.WriteLine("World!");
}
public void SayOK()
{
Console.WriteLine("OK!");
}
}
public class App
{
static void Main(string[] args)
{
A _a = new B();
_a.SayHello();
B _ab = (B)_a;
_ab.SayWorld();
Console.ReadKey();
}
}