c#多态性测试小例

基类

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Class1
    {
        private  int length;
        private  int weight;
        public int x;
        public int y;
        public int LENGTH
        {
            get
            {
                return length;
            }
            set
            {

                length = value < 0 ? -value : value;
            }
        }

        public int WEIGHT
        {
            get
            {
                return weight;
            }
            set
            {

                weight = value < 0 ? -value : value;
            }
        }

        public  int area;
        public Class1(int l, int w)
        {
            length = l;
            weight = w;
        }
       
        public  void SetArea()
        {
            area = length * weight;
        }
        public  virtual int Area()
        {
            return area;
        }
    }
}

 

派生类

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Subclass1:Class1
    {
        public Subclass1(int l,int w):base(l,w)
        {
        }
        public override int Area()
        {
            return base.Area()+10;
        }
      
    }
}

 

 

调用

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;//arraylist派生于array类

namespace ConsoleApplication1
{
    class Program
    {
       //学习多态性
      public static void Main(string[] args)
      {
          Class1 base1 = new Class1(1,1);
          Subclass1 sub1 = new Subclass1(10,10);

          //通过基类引用变量指向基类的对象及派生类的对象,导致在运行时调用派生类重写基类的方法area
          Class1 ref1;
          ref1 = base1;
          ref1.SetArea();
          Console.WriteLine(ref1.Area());
         
          ref1 = sub1;
          ref1.SetArea();
          Console.WriteLine(ref1.Area());
          Console.ReadKey();
      }
    }
   
}

 

 

小结;

        多态性是发生于继承情况下

       声明virtual及override

       声明一基类引用变量,通过其指向基类或派生类对象

       多态性最终运行是基类引用变量=右边的指向基类或派生类对象的重写方法

请使用浏览器的分享功能分享到微信等