多态之虚方法实现

3 篇文章 0 订阅

多态之虚方法步骤

	1)将父类的方法标记为虚方法,使用关键词virtual,这个函数可以被子类重新写一遍,override将子类标记;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _01多态//实现多态的三种方法:抽象类、虚方法、接口
{
    class Program
    {
        static void Main(string[] args)
        {
            //概念:让一个对象能够表现多重的状态(类型)
            Chinese chinese = new Chinese("刘德华");
            Japanese japanese = new Japanese("苍井空");
            Korea korea = new Korea("金秀贤");
            Person[] pers = new Person[3] { chinese, japanese, korea };
            for (int i = 0; i < pers.Length; i++)
            {
                pers[i].SayHello();//输出全是我是人类
                                   //    if(pers[i] is Chinese)
                                   //    {
                                   //        ((Chinese)pers[i]).SayHello();
                                   //    }
                                   //     else if (pers[i] is Japanese)
                                   //    {
                                   //        ((Japanese)pers[i]).SayHello();
                                   //    }
                                   //    else
                                   //    {
                                   //        ((Korea)pers[i]).SayHello();
                                   //    }
            }//解决代码冗余
            Console.ReadKey();
        }
    }
    public class Person
    {
        private string _name;//字段

        public string Name//属性
        {
            get => _name;
            set => _name = value;
        }
        public Person(string name)
        {
            this.Name = name;
        }
        public virtual void SayHello()
        {
            Console.WriteLine("我是人类");
        }
    }
    public class Chinese:Person
    {
        public Chinese(string name):base(name)//父类构造函数
        {
            
        }
        public override void SayHello()
        {
            Console.WriteLine("我是中国人,叫{0}", this.Name);
        }
    }
    public class Japanese : Person
    {
        public Japanese(string name) : base(name)//父类构造函数
        {
            
        }
        public override void SayHello()
        {
            Console.WriteLine("我是日本人,叫{0}", this.Name);
        }
    }
    public class Korea : Person
    {
        public Korea(string name) : base(name)//父类构造函数
        {
           
        }
        public override void SayHello()
        {
            Console.WriteLine("我是韩国人,叫{0}", this.Name);
        }
    }


}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值