C# 只允许单一继承。多重继承可以通过接口达到。
例子:
复制内容到剪贴板
代码:
class Parent{
}
class Child : Parent
虚函数
虚函数在 C# 中同样是用于实现多态的概念的,除了你要使用 override 关键字在子类中实现虚函数外。父类使用同样的 virtual 关键字。每个重写虚函数的类都使用 override 关键字。(译注:作者所说的“同样”,“除……外”都是针对 C# 和 C++ 而言的)
复制内容到剪贴板
代码:
class Shape { public virtual void Draw() { Console.WriteLine("Shape.Draw") ; } }
class Rectangle : Shape
{ public override void Draw() { Console.WriteLine("Rectangle.Draw"); } }
class Square : Rectangle { public override void Draw() { Console.WriteLine("Square.Draw"); } } class MainClass { static void Main(string[] args) { Shape[] shp = new Shape[3]; Rectangle rect = new Rectangle(); shp[0] = new Shape(); shp[1] = rect; shp[2] = new Square(); shp[0].Draw(); shp[1].Draw(); shp[2].Draw(); } } Output: Shape.Draw Rectangle.Draw Square.Draw |
使用“new”隐藏父类函数
你可以隐藏基类中的函数而在子类中定义其新版本。关键字 new 用于声明新的版本。思考下面的例子,该例是上一例子的修改版本。注意输出,我用 关键字 new 替换了 Rectangle 类中的关键字 override。
复制内容到剪贴板
代码:
class Shape { public virtual void Draw() { Console.WriteLine("Shape.Draw") ; } }
class Rectangle : Shape { public new void Draw() { Console.WriteLine("Rectangle.Draw"); } } class Square : Rectangle { //这里不用 override public new void Draw() { Console.WriteLine("Square.Draw"); } } class MainClass { static void Main(string[] args) { Console.WriteLine("Using Polymorphism:"); Shape[] shp = new Shape[3]; Rectangle rect = new Rectangle(); shp[0] = new Shape(); shp[1] = rect; shp[2] = new Square(); shp[0].Draw(); shp[1].Draw(); shp[2].Draw(); Console.WriteLine("Using without Polymorphism:"); rect.Draw(); Square sqr = new Square(); sqr.Draw(); } } Output: Using Polymorphism Shape.Draw Shape.Draw Shape.Draw Using without Polymorphism: Rectangle.Draw Square.Draw |
多态性认为 Rectangle 类的 Draw 方法是和 Shape 类的 Draw 方法不同的另一个方法,而不是认为是其多态实现。所以为了防止父类和子类间的命名冲突,我们只有使用 new 修饰符。
上一页 [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] ... 下一页 >>

【责编:Luzi】