C#学习笔记07:多态

来源:互联网 发布:关系型数据库四大特征 编辑:程序博客网 时间:2024/06/05 06:11

1、多态性概念

使用同一个名称,其依据Context不同,产生不同功能。如对象调用同一函数,随着引用实例不同,实现功能也不相同。

Shape shape=newCirlce();

      shape.area();

shape=new Rect();

      shape.area();

在OOP编程中,实现多态一般通过子类重写父类中虚函数或抽象函数来实现,

abstract class Shape{

    public abstractdouble area();

    public void disp(){

       …

    }

}

抽象类不能实例化.(基类)

class Circle :Shape{

    public overridedouble area(){

       ..

    }

 }

2、接口Interface定义与使用

   接口是一种特殊类,接口中只有抽象函数与抽象属性声明。

 1)接口定义

   interface IShape

    {

         double area();

         double length();

    }

    class Circle: IShape

    {

        private double r;

        public Circle() { }

        public Circle(double r)

        {

            this.r = r;

        }

        public  double area()

        {

            return Math.PI*r*r;

        }

        public double length()

        {

            return 2 * Math.PI* r;

        }

    }

    class Rect: IShape

    {

        private double w, h;

        public Rect() { }

        public Rect(double w, double h)

        {

            this.w = w; this.h = h;

        }

        public double area()

        {

            return w*h;

        }

        public double length()

        {

            return 2*(w+h);

        }

    }

 例:定义一个会飞接口

   interface ICanFly

    {

        void fly();

    }

    class Bird: ICanFly

    {

        public void fly()

        {

            Console.WriteLine("Bird Flying");

        }

    }

    class Plane: ICanFly

    {

        public void fly()

        {

            Console.WriteLine("Plane Flying");

        }

    }

    class Person

    {

    }

    class Ex1_1

    {

        static void makeFly(Objectobj)

        {

            //Console.WriteLine(obj.GetType());

            //Console.WriteLine(obj.ToString());

            if (obj is ICanFly)

            {

                ICanFly fly = (ICanFly)obj;

                fly.fly();

            }

            else

                Console.WriteLine("Can not fly!");

        }

        static void Main(string[] args)

        {

            Bird bird = new Bird();

            makeFly(bird);

            Plane plane = new Plane();

            makeFly(plane);

            Person person = new Person();

            makeFly(person);

            Console.ReadLine();

        }

    }

本章练习题下载地址:点此下载

原创粉丝点击