继承
基类和派生类
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。
C# 中创建派生类的语法如下:
<访问修饰符符> class <基类>{...}class <派生类> : <基类>{...}
class Rectangle :Shape
多态性
静态多态
您可以在同一个范围内对相同的函数名有多个定义。函数的定义必须彼此不同,可以是参数列表中的参数类型不同,也可以是参数个数不同。不能重载只有返回类型不同的函数声明。
下面的实例演示了几个相同的函数 print(),用于打印不同的数据类型:
using System;namespace PolymorphismApplication{class Printdata{void print(int i){Console.WriteLine("Printing int: {0}", i );}void print(double f){Console.WriteLine("Printing float: {0}" , f);}void print(string s){Console.WriteLine("Printing string: {0}", s);}static void Main(string[] args){Printdata p = new Printdata();// 调用 print 来打印整数p.print(5);// 调用 print 来打印浮点数p.print(500.263);// 调用 print 来打印字符串p.print("Hello C++");Console.ReadKey();}}}
当上面的代码被编译和执行时,它会产生下列结果:
Printing int: 5Printing float: 500.263Printing string: Hello C++
动态多态
先用abstract 定一个抽象类以及抽象类方法,然后在派生类里override方法
using System;namespace PolymorphismApplication{abstract class Shape{public abstract int area();}class Rectangle: Shape{private int length;private int width;public Rectangle( int a=0, int b=0){length = a;width = b;}public override int area (){Console.WriteLine("Rectangle 类的面积:");return (width * length);}}class RectangleTester{static void Main(string[] args){Rectangle r = new Rectangle(10, 7);double a = r.area();Console.WriteLine("面积: {0}",a);Console.ReadKey();}}}
先用virtual 定一个虚方法,然后在派生类里override该方法
using System;namespace PolymorphismApplication{class Shape{protected int width, height;public Shape( int a=0, int b=0){width = a;height = b;}public virtual int area(){Console.WriteLine("父类的面积:");return 0;}}class Rectangle: Shape{public Rectangle( int a=0, int b=0): base(a, b){}public override int area (){Console.WriteLine("Rectangle 类的面积:");return (width * height);}}class Triangle: Shape{public Triangle(int a = 0, int b = 0): base(a, b){}public override int area(){Console.WriteLine("Triangle 类的面积:");return (width * height / 2);}}class Caller{public void CallArea(Shape sh){int a;a = sh.area();Console.WriteLine("面积: {0}", a);}}class Tester{static void Main(string[] args){Caller c = new Caller();Rectangle r = new Rectangle(10, 7);Triangle t = new Triangle(10, 5);c.CallArea(r);c.CallArea(t);Console.ReadKey();}}}
动态多态性通过 抽象类 和 虚方法 实现的。
运算符重载
重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的。与其他函数一样,重载运算符有返回类型和参数列表。
例如,下面的函数,以自定义的box函数(盒子,函数有盒子的长宽高对象,以及求体积方法)为例,重载了加法运算。返回一个box对象:
public static Box operator+ (Box b, Box c){Box box = new Box();box.length = b.length + c.length;box.breadth = b.breadth + c.breadth;box.height = b.height + c.height;return box;}
上面的函数为用户自定义的类 Box 实现了加法运算符(+)。它把两个 Box 对象的属性相加,并返回相加后的 Box 对象。
接口(Interface)
public
接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。接口的实现与类的继承语法格式类似
接口比类的优势在于类在重载时比较复杂,接口从开始只定义了接口,每一个实例都必须描述方法下的具体动作,不需要“重写”操作。
