一个C#多态的例子下面是一个多态的例子,还有个被它引用的程序集,因为太长我就不写了.程序集说Shape是基类,其它的类都是派生类,并给出了计算每个形状的面积计算公式.我对这个例子很多地
来源:学生作业帮助网 编辑:作业帮 时间:2024/12/01 13:48:07
一个C#多态的例子下面是一个多态的例子,还有个被它引用的程序集,因为太长我就不写了.程序集说Shape是基类,其它的类都是派生类,并给出了计算每个形状的面积计算公式.我对这个例子很多地
一个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);
Shape[] shapes = new Shape[5];
shapes[0] = r;
shapes[1] = s;
shapes[2] = e;
shapes[3] = c;
shapes[4] = t;
foreach(Shape shape in shapes)
{
shape.Position = p;
PrintArea(shape);
}
}
}
}
一个C#多态的例子下面是一个多态的例子,还有个被它引用的程序集,因为太长我就不写了.程序集说Shape是基类,其它的类都是派生类,并给出了计算每个形状的面积计算公式.我对这个例子很多地
using System; //调用system类 和C下的include一样
using System.Drawing; //调用system.drawing类
using _05_Base; //调用自建类05_base
namespace _05_03 //命名空间 05_03
{
public class Class_05_03 //公有类05_03
{
public static void PrintArea(Shape shape)
//公有类 静态 无返回值类 PrintArea(内部数据成员shape,把shape这个单词指定为shape类型,就象int i)
{
Console.WriteLine("Area of {0} is : {1}", shape.Name, shape.Area);
//控制台输出 Area of {0} is : {1} 其中0为shape.Name的数据 1 为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();
// 分配一新的空间r ,用05_Base.Rectangle类化
r.Name = "Rectangle r";
r.Width = 10;
r.Height = 20;
//以上3行为新分配的空间r 写入其类的对应值
Square s = new Square();
s.Name = "Square s";
s.Side = 15;
//用Square 类化s 分配空间 赋值
Ellipse e = new Ellipse();
e.Name = "Ellipse e";
e.SemiMajorAxis = 10;
e.SemiMinorAxis = 5;
//用Ellipse类化e 分配空间 赋值
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);
// 这两个自己会看了把?
Shape[] shapes = new Shape[5];
shapes[0] = r;
shapes[1] = s;
shapes[2] = e;
shapes[3] = c;
shapes[4] = t;
foreach(Shape shape in shapes)
//Shape shape in shapes不懂这是什么意思
{
shape.Position = p;
PrintArea(shape);
}
}
}
}