zoukankan      html  css  js  c++  java
  • 实现接口与显式实现接口的区别

    原文:http://www.cnblogs.com/chenxizhang/archive/2008/08/22/1274265.html

    在实现接口的时候,VS提供了两个菜单,一个是"实现接口",一个是"显式实现接口",它们到底有何不一样呢

    我们来比较一下看看

    1.首先假设我们有一个接口

    public interface ICustomer
    {
        void SomeMethod();
    }

    2.如果是"实现接口",那么代码大致如下

    public class Customer:ICustomer
    {

        #region ICustomer 成员

        public void SomeMethod()
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    3.如果是"显式实现接口",那么代码大致如下

    public class Customer:ICustomer
    {

        #region ICustomer 成员

        void ICustomer.SomeMethod()
        {
            throw new NotImplementedException();
        }

        #endregion
    }

    大家看到差别了吧?显式实现的方式,那些方法都会加上一个前缀的。但是,这到底意味着什么呢?

    如果是实现接口

    public class DAL {
        /// <summary>
        /// 如果我们是直接实现接口的话,那么既可以用接口调用方法,也可以用具体类调用方法
        /// </summary>
        public void GetCustomer() {
            Customer customer = new Customer();
            customer.SomeMethod();
        }

        public void GetCustomer2() {
            ICustomer customer = new Customer();
            customer.SomeMethod();
        }
    }

    如果是显式实现接口

    public class DAL {
        /// <summary>
        /// 如果我们是显式实现接口的话,那么要访问里面的方法就只能是通过接口来调用,而不能通过具体类来做
        /// </summary>
        public void GetCustomer() {
            ICustomer customer = new Customer();
            customer.SomeMethod();
        }
    }

    现在大部分的系统为了保证扩展性,都广泛地使用接口。显式实现接口,可以隐藏具体类的复杂性。

  • 相关阅读:
    这些 Drawable 的小技巧,你都了解吗?
    Android 软键盘的显示和隐藏,这样操作就对了
    在 ReactNative 的 App 中,集成 Bugly 你会遇到的一些坑
    聊聊 Material Design 里,阴影的那些事儿!
    PAT 1069 1070 1071 1072
    PAT1021 Deepest Root
    关于素数:求不超过n的素数,素数的判定(Miller Rabin 测试)
    PAT《数据结构学习与实验指导》实验项目集 2-05 2-06 2-07 2-08
    LeetCode:Gas Station
    LeetCode:Candy
  • 原文地址:https://www.cnblogs.com/ghw0501/p/4802298.html
Copyright © 2011-2022 走看看