当建立一个类时,顺序员不需要完整从新编写新的数据成员和成员函数,只需要设想一个新的类,继续了已有的类的成员即可。这个已有的类被称为的基类,这个新的类被称为派生类。
继续的头脑完成了 属于(IS-A) 关联。比方,哺乳动物 属于(IS-A) 动物,狗 属于(IS-A) 哺乳动物,因而狗 属于(IS-A) 动物。
基类和派生类
一个类能够派生自多个类或接口,这意味着它能够从多个基类或接口继续数据和函数。
C# 中建立派生类的语法以下:
<acess-specifier> class <base_class>{ ... } class <derived_class> : <base_class>{ ... }
假定,有一个基类 Shape,它的派生类是 Rectangle:
using System;namespace InheritanceApplication{ class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // 派生类 class Rectangle: Shape { publicint getArea() { return (width * height); } } class RectangleTester { static voidMain(string[] args) { Rectangle Rect = new Rectangle(); Rect.setWidth(5); Rect.setHeight(7); // 打印对象的面积 Console.WriteLine("总面积: {0}", Rect.getArea()); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会发生以下效果:
总面积: 35
基类的初始化
派生类继续了基类的成员变量和成员要领。因而父类对象应在子类对象建立之前被建立。您能够在成员初始化列表中举行父类的初始化。
下面的顺序演示了这点:
using System;namespace RectangleApplication{ class Rectangle { // 成员变量 protected double length; protected double width; public Rectangle(double l, double w) { length = l; width = w; } public double GetArea() { return length * width; } public void Display() { Console.WriteLine("长度: {0}", length); Console.WriteLine("宽度: {0}", width); Console.WriteLine("面积: {0}", GetArea()); } }//end class Rectangle class Tabletop : Rectangle { private double cost; publicTabletop(double l, double w) : base(l, w) { } public double GetCost() { double cost; cost = GetArea() * 70; return cost; } public void Display() { base.Display(); Console.WriteLine("本钱: {0}", GetCost()); } } classExecuteRectangle { static void Main(string[] args) { Tabletop t = new Tabletop(4.5,7.5); t.Display(); Console.ReadLine(); } }}
当上面的代码被编译和执行时,它会发生以下效果:
长度: 4.5宽度: 7.5面积: 33.75本钱: 2362.5
C# 多重继续
多重继续指的是一个种别能够同时从多于一个父类继续行动与特性的功用。与单一继续相对,单一继续指一个种别只能够继续自一个父类。
C# 不支持多重继续。然则,您能够运用接口来完成多重继续。下面的顺序演示了这点:
using System;namespace InheritanceApplication{ class Shape { public void setWidth(int w) { width = w; } public void setHeight(int h) { height = h; } protected int width; protected int height; } // 基类 PaintCost public interface PaintCost { int getCost(int area); } // 派生类 class Rectangle : Shape, PaintCost { public int getArea() { return (width * height); } public int getCost(int area) { return area * 70; } } class RectangleTester { static void Main(string[] args) { Rectangle Rect = new Rectangle(); int area; Rect.setWidth(5); Rect.setHeight(7); area = Rect.getArea(); // 打印对象的面积 Console.WriteLine("总面积: {0}", Rect.getArea()); Console.WriteLine("油漆总本钱: ${0}" , Rect.getCost(area)); Console.ReadKey(); } }}
当上面的代码被编译和执行时,它会发生以下效果:
总面积: 35油漆总本钱: $2450
更多C# 继续相干文章请关注ki4网!