实名认证用户熊川湘 身份证号码430811198506290914

接口的实便

接口就是一个先签协议(接口定义),后实现。  
  本示例显示声明一个   IDimensions   接口和一个   Box   类,该类显式实现接口成员   Length   和   Width。通过接口实例   myDimensions   访问这些成员。  
   
  //   explicit1.cs  
  interface   IDimensions    
  {  
        float   Length();  
        float   Width();  
  }  
   
  class   Box   :   IDimensions    
  {  
        float   lengthInches;  
        float   widthInches;  
   
        public   Box(float   length,   float   width)    
        {  
              lengthInches   =   length;  
              widthInches   =   width;  
        }  
        //   Explicit   interface   member   implementation:    
        float   IDimensions.Length()    
        {  
              return   lengthInches;  
        }  
        //   Explicit   interface   member   implementation:  
        float   IDimensions.Width()    
        {  
              return   widthInches;              
        }  
   
        public   static   void   Main()    
        {  
              //   Declare   a   class   instance   "myBox":  
              Box   myBox   =   new   Box(30.0f,   20.0f);  
              //   Declare   an   interface   instance   "myDimensions":  
              IDimensions   myDimensions   =   (IDimensions)   myBox;  
              //   Print   out   the   dimensions   of   the   box:  
              /*   The   following   commented   lines   would   produce   compilation    
                    errors   because   they   try   to   access   an   explicitly   implemented  
                    interface   member   from   a   class   instance:                                       */  
              //System.Console.WriteLine("Length:   {0}",   myBox.Length());  
              //System.Console.WriteLine("Width:   {0}",   myBox.Width());  
              /*   Print   out   the   dimensions   of   the   box   by   calling   the   methods    
                    from   an   instance   of   the   interface:                                                   */  
              System.Console.WriteLine("Length:   {0}",   myDimensions.Length());  
              System.Console.WriteLine("Width:   {0}",   myDimensions.Width());  
        }  
  }  
  输出  
  Length:   30  
  Width:   20  

实例二:

interface   Itest  
  {  
      string   ShowText();  
  }  
   
  class   class1:Itest  
  {  
      class1(){}  
      string   ShowText()  
      {  
          return   "Class1   Show   Text!";  
      }  
   
  }  
   
  class   class2:Itest  
  {  
      class2(){}  
      string   ShowText()  
      {  
          return   "Class2   Show   Text!";  
      }  
   
  }  
   
  可以写个函数:  
  void   ShowTextTest(Itest   itest)  
  {  
      string   temp;  
      temp=itest.ShowText();  
  }   
      分别把class1和class2的实例传给ShowTextTest(cls1)会有不同的结果。
  接口也可以实现多态啊!

posted @ 2010-02-25 13:59  浪达短信群发  阅读(148)  评论(0编辑  收藏  举报