您的位置:首页 > 编程语言 > C#

C#基础:多态:基类可以定义并实现虚(virtual)方法,派生类可以重写(override)这些方法

2013-02-19 19:54 716 查看
原理:基类可以定义并实现虚(virtual)方法,派生类可以重写(override)这些方法

实例代码:

class Shape

{

//

public int X{get;private set; }

public int Y{get;private set;}

public int Height{get;set;}

public int Width{get;set;}

//

public virtual void Draw()

{

Console.WriteLine("Performing base class drawing tasks");

}

}

class Circle : Shape

{

public override void Draw()

{

// Code to draw a circle...

Console.WriteLine("Drawing a circle");

base.Draw();

}

}

class Rectangle : Shape

{

public override void Draw()

{

// Code to draw a rectangle...

Console.WriteLine("Drawing a rectangle");

base.Draw();

}

}

class Triangle : Shape

{

public override void Draw()

{

// Code to draw a triangle...

Console.WriteLine("Drawing a triangle");

base.Draw();

}

}

class Program

{

static void Main(string[] args)

{

List<Shape> shapes = new List<Shape>();

shapes.Add(new Rectangle());

shapes.Add(new Triangle());

shapes.Add(new Circle());

foreach (Shape s in shapes)

{

s.Draw();

}

Console.WriteLine("press any key to exit.");

Console.ReadKey();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐