标题: c#多态的例子 [打印本页] 作者: 小太阳 时间: 2014-6-23 01:19 标题: c#多态的例子 下面是一个多态的例子,还有个被它引用的程序集,因为太长我就不写了。程序集说Shape是基类,其它的类都是派生类,并给出了计算每个形状的面积计算公式。我对这个例子很多地方不太明白,请告诉我每句程序的意思,谢了。
using System;
using System.Drawing;
using _05_Base;
namespace _05_03
{
public class Class_05_03
{
public static void PrintArea(Shape shape)
{
Console.WriteLine("Area of {0} is : {1}", shape.Name, shape.Area);
}
public static void Main(String[] args)
{
Point p = new Point(0, 0);
_05_Base.Rectangle r = new _05_Base.Rectangle();
r.Name = "Rectangle r";
r.Width = 10;
r.Height = 20;
Square s = new Square();
s.Name = "Square s";
s.Side = 15;
Ellipse e = new Ellipse();
e.Name = "Ellipse e";
e.SemiMajorAxis = 10;
e.SemiMinorAxis = 5;
Circle c = new Circle();
c.Name = "Circle c";
c.Radius = 6;
Triangle t = new Triangle();
t.Name = "Triangle t";
t.Point1 = new Point(3, 3);
t.Point2 = new Point(3, 0);
foreach(Shape shape in shapes)
{
shape.Position = p;
PrintArea(shape);
}
}
}
}作者: The_Enternal 时间: 2014-6-23 18:15
建议你把完成的程序代码都贴出来,里面有几个是自己定义的类,没有见到具体的代码谁也不知道这个类的对象初始化的时候搞了什么!作者: 永远的小飞侠 时间: 2014-6-24 17:12
using System;
using System.Drawing;
using _05_Base;
namespace _05_03
{
public class Class_05_03
{
public static void PrintArea(Shape shape)
{ //这个应该是根据传入的一个Shape类的对象 打印出对象shape的面积
Console.WriteLine("Area of {0} is : {1}", shape.Name, shape.Area);
}
public static void Main(String[] args)
{
Point p = new Point(0, 0); //初始化一个Point对象p和坐标(0,0)
_05_Base.Rectangle r = new _05_Base.Rectangle(); //初始化一个Rectangle 图形,定义名字,长和宽
r.Name = "Rectangle r";
r.Width = 10;
r.Height = 20;
Square s = new Square(); //初始化一个 Square 图形,定义名字和side
s.Name = "Square s";
s.Side = 15;
Ellipse e = new Ellipse(); //初始化一个 Ellipse 图形,定义名字,SemiMajorAxis 和SemiMinorAxi
e.Name = "Ellipse e";
e.SemiMajorAxis = 10;
e.SemiMinorAxis = 5;
Circle c = new Circle(); //初始化一个 Circle 图形,定义半径
c.Name = "Circle c";
c.Radius = 6;
Triangle t = new Triangle(); //初始化一个 Triangle 图形,定义名字,和两个点 的坐标
t.Name = "Triangle t";
t.Point1 = new Point(3, 3);
t.Point2 = new Point(3, 0);