1、定义多边形类Polygon,在类中定义字段、属性和抽象方法;基类Polygon创建派类Triangle,Square和Pentagon,在派生类中实现方法重载d程序中实例化类的对象并且调用类的方法实现多态性
实例:
******
program.cs类
******
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test_16
{
class Program
{
static void Main(string[] args)
{
Polygon polygon;
polygon = new Triangle();
polygon.Length = 3;
Console.WriteLine(polygon.GetPeri ());
polygon = new Square();
polygon.Length = 2;
Console.WriteLine(polygon .GetPeri ());
polygon = new Pentagon();
Console.WriteLine(polygon .GetPeri ());
Console.WriteLine("请回车键结束");
}
}
}
*******
Pentagon.cs类
********
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test_16
{
public class Pentagon:Polygon
{
public Pentagon()
{
Sides = 5;
}
public override string GetPeri()
{
return "The perimeter of pentagon is " + Convert.ToString(Length * Sides);
}
}
}
******
Triangle.cs类
******
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test_16
{
public class Triangle :Polygon
{
public Triangle()
{
Sides = 3;
}
public override string GetPeri()
{
return "The perimeter of triangle is " + Convert.ToString(Sides * Length);
}
}
}
******
Square.cs类
******
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test_16
{
public class Square :Polygon
{
public Square ()
{
Sides =4;
}
public override string GetPeri()
{
return "The perimeter of square is " + Convert.ToString(Length * Sides);
}
}
}
****
Polygon.cs
****
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test_16
{
public abstract class Polygon
{
private int m_length;
private int m_sides;
public int Length
{
get { return m_length; }
set { m_length = value; }
}
public int Sides
{
get { return m_sides; }
set { m_sides = value; }
}
public Polygon()
{
Length = 1;
}
public abstract string GetPeri();
}
}
运行结果
OK呵呵太简单了,加油