C#编程和Visual Studio使用技巧(下)

2019-12-26 13:40:14刘景俊
  •   </CODE>   ?

    3、显性和隐性接口实现

    这很重要吗?是的,非常重要,你知道它们之间的语法差异吗?其实它们存在根本性的区别。类上的隐性接口实现默认是一个公共方法,在类的对象或接口上都可以访问。而类上的显性接口实现默认是一个私有方法,只能通过接口访问,不能通过类的对象访问。下面是示例代码:
     

    1. <CODE>     
    2.  INTERFACE    public interface IMyInterface  
    3.  {    void MyMethod(string myString);  
    4.  }     
    5.  CLASS THAT IMPLEMENTS THE INTERFACE IMPLICITLY    public MyImplicitClass: IMyInterface  
    6.  {    public void MyMethod(string myString)  
    7.  {    ///  
    8.  }    }  
    9.     CLASS THAT IMPLEMENTS THE INTERFACE EXPLICITLY  
    10.  public MyExplicitClass: IMyInterface    {  
    11.  void IMyInterface.MyMethod(string myString)    {  
    12.  ///    }  
    13.  }     
    14.  MyImplicitClass instance would work with either the class or the Interface:    MyImplicitClass myObject = new MyImplicitClass();  
    15.  myObject.MyMethod("");    IMyInterface myObject = new MyImplicitClass();  
    16.  myObject.MyMethod("");     
    17.  MyExplicitClass would work only with the interface:    //The following line would not work.  
    18.  MyExplicitClass myObject = new MyExplicitClass();    myObject.MyMethod("");  
    19.  //This will work    IMyInterface myObject = new MyExplicitClass();  
    20.  myObject.MyMethod("");