欢迎光临
我们一直在努力

C#语言初级入门(3)-.NET教程,C#语言

建站超值云服务器,限时71元/月

在这最后一个例子中,我们来看看c#的抽象和多态性。首先我们来定义一下这两个新的术语。抽象(abstract)通过从多个对象提取出公共部分并把它们并入单独的抽象类中实现。在本例中我们将创建一个抽象类shape(形状)。每一个形状都拥有返回其颜色的方法,不论是正方形还是圆形、长方形,返回颜色的方法总是相同的,因此这个方法可以提取出来放入父类shape。这样,如果我们有10个不同的形状需要有返回颜色的方法,现在只需在父类中创建一个方法。可以看到使用抽象使得代码更加简短。

   在面向对象编程领域中,多态性(polymorphism)是对象或者方法根据类的不同而作出不同行为的能力。在下面这个例子中,抽象类shape有一个getarea()方法,针对不同的形状(圆形、正方形或者长方形)它具有不同的功能。

   下面是代码:

public abstract class shape {
   protected string color;
   public shape(string color) {
      this.color = color;
   }
   public string getcolor() {
      return color;
   }
   public abstract double getarea();
}

public class circle : shape {
   private double radius;
   public circle(string color, double radius) : base(color) {
      this.radius = radius;
   }
   public override double getarea() {
      return system.math.pi * radius * radius;
   }
}

public class square : shape {
   private double sidelen;
   public square(string color, double sidelen) : base(color) {
      this.sidelen = sidelen;
   }
   public override double getarea() {
      return sidelen * sidelen;
   }
}

/*
public class rectangle : shape
…略…
*/

public class example3
{
   static void main()
   {
     shape mycircle = new circle("orange", 3);
     shape myrectangle = new rectangle("red", 8, 4);
     shape mysquare = new square("green", 4);
     system.console.writeline("圆的颜色是" + mycircle.getcolor()
                    + "它的面积是" + mycircle.getarea() + ".");
     system.console.writeline("长方形的颜色是" + myrectangle.getcolor()
                    + "它的面积是" + myrectangle.getarea() + ".");
     system.console.writeline("正方形的颜色是" + mysquare.getcolor()
                    + "它的面积是" + mysquare.getarea() + ".");
   }
}

  

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » C#语言初级入门(3)-.NET教程,C#语言
分享到: 更多 (0)

相关推荐

  • 暂无文章