一个C#多态的例子

来源:百度知道 编辑:UC知道 时间:2024/09/25 13:15:28
下面是一个多态的例子,还有个被它引用的程序集,因为太长我就不写了。程序集说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;

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 分配空间 赋值