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

//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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值