- 爱易网页
 
                        - 
                            C#教程
 
                        - 关于接口的一个小疑点 
 
                         
                    
                    
                    日期:2014-05-18  浏览次数:21138 次 
                    
                        
                         关于接口的一个小问题
//   keyword_interface_2.cs 
 //   Interface   implementation 
 using   System; 
 interface   IPoint 
 { 
          //   Property   signatures: 
          int   x 
          { 
                   get; 
                   set; 
          } 
  
          int   y 
          { 
                   get; 
                   set; 
          } 
 } 
  
 class   Point   :   IPoint 
 { 
          //   Fields: 
          private   int   _x; 
          private   int   _y; 
  
          //   Constructor: 
          public   Point(int   x,   int   y) 
          { 
                   _x   =   x; 
                   _y   =   y; 
          } 
  
          //   Property   implementation: 
          public   int   x 
          { 
                   get 
                   { 
                            return   _x; 
                   } 
  
                   set 
                   { 
                            _x   =   value; 
                   } 
          } 
  
          public   int   y 
          { 
                   get 
                   { 
                            return   _y; 
                   } 
                   set 
                   { 
                            _y   =   value; 
                   } 
          } 
 } 
  
 class   MainClass 
 { 
          static   void   PrintPoint(IPoint   p) 
          { 
                   Console.WriteLine( "x={0},   y={1} ",   p.x,   p.y); 
          } 
  
          static   void   Main() 
          { 
                   Point   p   =   new   Point(2,   3); 
                   Console.Write( "My   Point:    "); 
                   PrintPoint(p); 
          } 
 } 
  
  
 在构造PrintPoint()方法时为什么使用的是接口的对象作为参数。接口不是不能实例化的么?那为什么能够用它来作为方法的参数呢? 
------解决方案--------------------
他将接口作为参数不是不对,虽然接口不能实例化,但是 继承了接口的类 实例化后,把类赋值给接口变量,这样就可以调用了。 
 比如: 
 interface IPoint 
 { 
    // Property signatures: 
    int x 
    { 
       get; 
       set; 
    } 
  
    int y 
    { 
       get; 
       set;