接口的显示实现和隐式实现一点笔记

来源:互联网 发布:centos一键安装lnmp 编辑:程序博客网 时间:2024/06/05 21:55

博客迁移

隐式实现 不知道成员的归属
显示实现 显示指定成员的归属(通过 接口名.成员 )


显式实现避免了成员归属混淆不清的情况,特别是多个接口中有相同的成员,或者接口中成员和类自己的成员冲突的情况。


隐式实现 public interface IBaseInterface1    {        void Method1();        void Method2();    }    public interface IBaseInterface2    {        void Method1();        void Method2();    }    public class Test : IBaseInterface1, IBaseInterface2    {        public void Method1()        {        }        public void Method2()        {        }    }

显式实现public interface IBaseInterface1    {        void Method1();        void Method2();    }    public interface IBaseInterface2    {        void Method1();        void Method2();    }    public class Test1 : IBaseInterface1,IBaseInterface2    {        void IBaseInterface1.Method1()        {        }        void IBaseInterface1.Method2()        {        }        void IBaseInterface2.Method1()        {        }        void IBaseInterface2.Method2()        {        }    }

有时某个类往往会继承多个接口,而接口中往往会有一些相同名称、参数与类型的值。通过显式接口实现可以为避免一些不必要的歧义。

隐式接口实现,类和接口都可访问接口中方法。显式接口实现,只能通过接口访问。


注意:显式实现的成员不能用public来修饰,所以该成员不能通过该类来访问,只能通过接口访问。
比如


Test1 test = new Test1();            test.Method1();//调用会出错 这样调用是调不到的            IBaseInterface1 itest = test as Test1;            itest.Method1();

结:2015.7.30改

1 0
原创粉丝点击