C#面向对象(四)虚方法实现多态

一、虚方法实现多态

1,创建一个people基类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 继承之抽象类
{
   public class people
     {

        public virtual void SayHi()//定义一个SayHi的虚方法
        { }
    }
}

2.创建两个子类Student.cs和Teacher.cs继承基类people

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 继承之抽象类
{
    class Student : people
    {
        public override void SayHi()      //重写
        {
            Console.WriteLine("你好我是学生");
        }
    }
}
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace 继承之抽象类
    {
        class Teacher:people  //继承Peoper类
        {
            public override void SayHi()   //重写
            {
                Console.WriteLine("你好我是老师");
            }
        }
    }

输出结果:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 继承之抽象类
{
    class Program
    {
       static List<people> peopers = new List<people>();  //定义一个泛型实例

        public static void InitData()
        {
            Student st = new Student();

            Teacher tc = new Teacher();

            peopers.Add(st);
            peopers.Add(tc);

        }
        public static void Start()
        {
            foreach (people peoper in peopers)  //遍历泛型实例
            {
                peoper.SayHi();
            }
        }

        static void Main(string[] args)
        {
            InitData();
            Start();
            Console.ReadLine();
        }
    }
}

posted @ 2014-01-26 12:40  LiuHuaTao  阅读(371)  评论(0编辑  收藏  举报