C#控制台基础 函数的参数是接口 实现接口的类都可以作为参数,很好用

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#控制台基础 函数的参数是接口 实现接口的类都可以作为参数,很好用相关的知识,希望对你有一定的参考价值。

1、代码

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

namespace ConsoleApplication1
{
    //为了便于观看,我就把接口和类都写在一个.cs文件中了
    public interface ISay
    {
        void Say();
    }
    class Student : ISay
    {
        public void Say()
        {
            Console.WriteLine("我是一个学生,我的任务是学习");
        }
    }
    class Teacher : ISay
    {
        public void Say()
        {
            Console.WriteLine("我是一个老师,我的任务是教书育人");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Introduce(new Student());
            Introduce(new Teacher());
            Console.ReadKey();
        }

        public static void Introduce(ISay h)
        {
            h.Say();
        }
    }

}

 

 

2、效果

技术分享

 

以上是关于C#控制台基础 函数的参数是接口 实现接口的类都可以作为参数,很好用的主要内容,如果未能解决你的问题,请参考以下文章