A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小太阳 中级黑马   /  2014-6-23 01:19  /  1499 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

下面是一个多态的例子,还有个被它引用的程序集,因为太长我就不写了。程序集说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);
   }
  }
}
}

评分

参与人数 1技术分 +1 收起 理由
czwanglei + 1

查看全部评分

3 个回复

倒序浏览
建议你把完成的程序代码都贴出来,里面有几个是自己定义的类,没有见到具体的代码谁也不知道这个类的对象初始化的时候搞了什么!
回复 使用道具 举报
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);

   Shape[] shapes = new Shape[5]; //定义一个基类Shape的数组,把刚初始化的几个派生类的对象放到数组里
   shapes[0] = r;
   shapes[1] = s;
   shapes[2] = e;
   shapes[3] = c;
   shapes[4] = t;

   foreach(Shape shape in shapes) //遍历Shape数组,打印出面积
   {
    shape.Position = p;
    PrintArea(shape);
   }
  }
}
}


应该就这么多了吧,还有什么问题一起交流!

评分

参与人数 1技术分 +1 收起 理由
czwanglei + 1

查看全部评分

回复 使用道具 举报

当有人给你回复后,请你及时把帖子编辑为提问结束,这样版主才给你加技术分
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马