c#面向对象特征(2)之多态

来源:互联网 发布:南京凶宅数据库 编辑:程序博客网 时间:2024/05/21 16:22
//c#的静态多态是指在编译的时候就实现了多态,动态多态是在执行时才知道的。
以下是静态多态
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintHello();
            PrintHello("world");

            //检测加法运算符的重载
            Complex c1 = new Complex();
            Complex c2 = new Complex();
            c1.Number = 2;
            c2.Number = 3;
            Console.WriteLine((c1+c2).Number);

            Console.ReadLine();
        }

        //c#的静态多态是指在编译的时候就实现了多态,动态多态是在执行时才知道的

        //方法的重载
        public static void PrintHello()
        {
            Console.WriteLine("Hello");
        }

        public static void PrintHello(string toWho)
        {
            Console.WriteLine("Hello {0}", toWho);
        }   
    }

    //运算符的重载

    class Complex {
        public int Number { get; set; }

        public static Complex operator +(Complex c1, Complex c2) {
            Complex c = new Complex();
            c.Number = c1.Number + c2.Number;
            return c;
        }
    }

}

2.动态多态
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //通过重写实现多态
            Human human1 = new Man();
            Human human2 = new Woman();
            human1.CleanRoom();//输出Man的效果
            human2.CleanRoom();//输出Woman的效果


            //重写class Complex中的tostring方法
            Complex c = new Complex();
            c.Number = 10;
            Console.WriteLine(c);//WriteLine方法直接调用tostring方法
            Console.ReadLine();
        }
    }

    //以下类是通过《重写》来实现动态多态
    class Human {
        public virtual void CleanRoom()
        {
            Console.WriteLine("Human clean room!");
        }
    }

    class Man :Human{
        public override void CleanRoom()
        {
            Console.WriteLine("Man clean room!");        
        }
    }

    class Woman : Human
    {
        public override void CleanRoom()
        {
            Console.WriteLine("Woman clean room!");
        }
    }

    class Complex {
        public int Number { get; set; }

        //重写tostring方法:可以实现自己各种想要的功能,这里是实现将数字打印的功能。
        public override string ToString()
        {
            return Number.ToString();
        }
    }


}

0 0
原创粉丝点击