C#继承
继承与封装和多态被统称为面向对象编程的三大特性,本节我们主要来介绍一下继承这一特性。
在创建一个新类时,我们可以使用这个新定义的类继承一个已有的类,通过继承可以在创建新类时重用、扩展和修改被继承类中定义的成员。被继承的类称为“基类(父类)”,继承基类的类称为“派生类(子类)”。
需要注意的是,C# 中只支持单继承,也就是说一个派生类只能继承一个基类,但是继承是可以传递的,例如 ClassC 继承了 ClassB,而 ClassB 继承了 ClassA,那么 ClassC 将继承 ClassB 和 ClassA 中的所有成员。
1、基类和派生类
要使用一个类继承另一个类需要使用到冒号:,如下所示:
class 派生类 : 基类{
... ...
}
【示例】下面通过一个示例来演示一下基类和派生类的实现:
using System;
namespace net.yinzhong
{
class Demo
{
static void Main(string[] args)
{
Rectangle oblong = new Rectangle();
oblong.setWidth(3);
oblong.setHeight(4);
int area = oblong.getArea();
Console.WriteLine("长方形的面积为:{0}", area);
}
}
// 基类
class Shape{
protected int width, height;
public void setWidth(int w){
width = w;
}
public void setHeight(int h){
height = h;
}
}
// 派生类
class Rectangle : Shape{
public int getArea(){
return width*height;
}
}
}
运行结果如下:
长方形的面积为:12
2、多重继承
与单继承相反,多重继承则是指一个类可以同时继承多个基类,C# 并不支持多重继承,但是可以借助接口来实现多重继承。下面就通过一个示例来演示一下:
using System;
namespace net.yinzhong
{
class Demo
{
static void Main(string[] args)
{
Rectangle oblong = new Rectangle();
oblong.setWidth(3);
oblong.setHeight(4);
int area = oblong.getArea();
int girth = oblong.getGirth();
Console.WriteLine("长方形的面积为:{0}", area);
Console.WriteLine("长方形的周长为:{0}", girth);
}
}
// 基类
class Shape{
protected int width, height;
public void setWidth(int w){
width = w;
}
public void setHeight(int h){
height = h;
}
}
// 定义接口
public interface Perimeter{
int getGirth();
}
// 派生类
class Rectangle : Shape, Perimeter{
public int getArea(){
return width*height;
}
public int getGirth(){
return (width+height)*2;
}
}
}
运行结果如下:
长方形的面积为:12 长方形的周长为:14
关于接口的相关知识会在后面详细介绍,这里大家了解即可。

