首页 > 其他 > 详细

C#面向对象(三)接口实现多态

时间:2014-01-26 15:40:19      阅读:374      评论:0      收藏:0      [点我收藏+]

一、如何用接口实现多态?

1.定义一个接口。

bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 继承之抽象类
{

    public interface people  //定义一个接口People
    {
       
        void SayHi();   //定义一个SayHi方法

    }
}
bubuko.com,布布扣

2.创建两个类Student.c和Teacher.cs继承接口

bubuko.com,布布扣
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 继承之抽象类
{
    class Student:people  //继承接口Peoper
    {

        public void SayHi()
        {
            Console.WriteLine("你好我是学生");
        }
    }
}
bubuko.com,布布扣
bubuko.com,布布扣
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace 继承之抽象类
    {
        class Teacher:people  //继承接口Peoper
        {
            public void SayHi()
            {
                Console.WriteLine("你好我是老师");
            }
        }
    }
bubuko.com,布布扣

3.创建一个program.cs类用来输出结果  

bubuko.com,布布扣
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();
        }
    }
}
bubuko.com,布布扣

输出结果:

bubuko.com,布布扣

C#面向对象(三)接口实现多态

原文:http://www.cnblogs.com/Lhuatao/p/3533899.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!