一、接口可以干嘛

       我们知道,接口的本质是一个约束规范,委托是方法纵向(形式上)的封装,接口是不同方法横向(广度)的封装

接口中不能有变量,但是可以有属性方法。常见的,我们可以用接口:

1、实现需求方的方法

2、接口作为参数,实现对不同类的解耦,下面是常见的男女类

    public interface ISay
    {
        void Say();
    }

    public class Man:ISay
    {
        public void Say()
        {
            Console.WriteLine("你好,我是男士!");
        }
    }

    public class Woman : ISay
    {
        public void Say()
        {
            Console.WriteLine("你好,我是女士!");
        }
    }

    public class Peole
    {
        public void Say(ISay iPeople)
        {
            iPeople.Say();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Man man = new Man();
            Woman woman = new Woman();
            Peole peole = new Peole();
            peole.Say(man);
            peole.Say(woman);
            Console.ReadLine();
        }
    }
View Code

相关文章: