c#多型性測試小例

wisdomone1發表於2012-03-18

基類

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

       宣告一基類引用變數,透過其指向基類或派生類物件

       多型性最終執行是基類引用變數=右邊的指向基類或派生類物件的重寫方法

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/9240380/viewspace-718875/,如需轉載,請註明出處,否則將追究法律責任。

相關文章