C#多态实例

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呵呵太简单了,加油

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值