C#笔记⑨——接口

一、简单的接口实现,解决紧耦合现象

点击查看代码
    class Test
    {
    static void Main(string[] arg)
    {
        var user=new User(new SangSun());
        user.UsePhone();
    }
    }

    class User
    {
        private Iphone myphone;
        public User(Iphone iphone)
        {
            myphone=iphone;
        }

        public void UsePhone()
        {
            myphone.Call();
            myphone.PickUp();
        }
    }

    interface Iphone
    {
        void Call();
        void PickUp();
    } 

    class SangSun:Iphone
    {
        public void Call()
        {
            System.Console.WriteLine("Let me show your SS");
        }

        public void PickUp()
        {
            System.Console.WriteLine("SS was PickUp");
        }
    }

    class OnePuls:Iphone
    {
        public void Call()
        {
            System.Console.WriteLine("Let me show your Onepuls");
        }

        public void PickUp()
        {
            System.Console.WriteLine("Onepuls was PickUp");
        }
    }
点击查看代码
    class Test
    {
    static void Main(string[] arg)
    {
        var product=new ZeskFan(new Engine());
        product.Test();
    }
    }

    interface IEngine
    {
        int GetPower();
    }
    class Engine:IEngine
    {
        private int power;
        public int GetPower()
        {
            return this.power=100;
        }
    }

    class ZeskFan
    {
        private IEngine engine; //从类转为接口
        public ZeskFan(IEngine engine1)
        {
            this.engine=engine1;
        }

        public void Test()
        {
            if(engine.GetPower()<0)
            {
                System.Console.WriteLine("Low Power");
            }
            else if(engine.GetPower()<100)
            {
                System.Console.WriteLine("Normal");
            }
            else if(engine.GetPower()<200)
            {
                System.Console.WriteLine("Waring");
            }
        }
    }

二、显式实现

将某些实现的方法隐藏

点击查看代码
    class Test
    {
    static void Main(string[] arg)
    {
        var wk=new WarmKiellr();
        wk.Love();
        //方法一
        // IKiller killer=wk;
        // killer.Kill(); 
        //方法二
        // IKiller killer=new WarmKiellr();
        // killer.Kill();
    }
    }

    interface IGentleman
    {
        void Love();
    }

    interface IKiller
    {
        void Kill();
    }

    class WarmKiellr:IGentleman,IKiller
    {
        public void Love()
        {
            System.Console.WriteLine("Love");
        }

        void IKiller.Kill() //显式接口,不能有public
        {
            System.Console.WriteLine("Kill");
        }

    }
posted @ 2022-02-07 13:37  Ariaaaaa  阅读(6)  评论(0)    收藏  举报