你的位置:首页 > ASP.net教程

[ASP.net教程]接口里不能包括字段,构造函数,析构函数,静态成员或常量等,否则会导致错误


定义一个借口,接口封装了矩形的长和宽,而且还包含一个自定义的方法以计算矩形的面积。然后定义一个类,继承自该接口,在该类中实现接口中自定义方法。

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace Test06 7 { 8 interface ImyInterface 9 {10 /// <summary>11 /// 长12 /// </summary>13 int Width14 {15 get;16 set;17 }18 /// <summary>19 /// 宽20 /// </summary>21 int Height22 {23 get;24 set;25 }26 /// <summary>27 /// 计算矩形面积28 /// </summary>29 int Area();30 }31 class Program : ImyInterface//继承自接口32 {33 private int width = 0;34 private int height = 0;35 /// <summary>36 /// 长37 /// </summary>38 public int Width39 {40 get41 {42 return width;43 }44 set45 {46 width = value;47 }48 }49 /// <summary>50 /// 宽51 /// </summary>52 public int Height53 {54 get55 {56 return height;57 }58 set59 {60 height = value;61 }62 }63 /// <summary>64 /// 计算矩形面积65 /// </summary>66 public int Area(int Width,int Height)67 {68 return Width * Height;69 }70 static void Main(string[] args)71 {72 Program program = new Program();//实例化Program类对象73 ImyInterface imyinterface = program;//使用派生类对象实例化接口ImyInterface74 imyinterface.Width = 5;//为派生类中的Width属性赋值75 imyinterface.Height = 3;//为派生类中的Height属性赋值76 Console.WriteLine("矩形的面积为:" + imyinterface.Area(3,5));77 }78 }79 }

下面是正确的:
 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5  6 namespace Test06 7 { 8   interface ImyInterface 9   {10     /// <summary>11     /// 长12     /// </summary>13     int Width14     {15       get;16       set;17     }18     /// <summary>19     /// 宽20     /// </summary>21     int Height22     {23       get;24       set;25     }26     /// <summary>27     /// 计算矩形面积28     /// </summary>29     int Area();30   }31   class Program : ImyInterface//继承自接口32   {33     int width = 0;34     int height = 0;35     /// <summary>36     /// 长37     /// </summary>38     public int Width39     {40       get41       {42         return width;43       }44       set45       {46         width = value;47       }48     }49     /// <summary>50     /// 宽51     /// </summary>52     public int Height53     {54       get55       {56         return height;57       }58       set59       {60         height = value;61       }62     }63     /// <summary>64     /// 计算矩形面积65     /// </summary>66     public int Area()67     {68       return Width * Height;69     }70     static void Main(string[] args)71     {72       Program program = new Program();//实例化Program类对象73       ImyInterface imyinterface = program;//使用派生类对象实例化接口ImyInterface74       imyinterface.Width = 5;//为派生类中的Width属性赋值75       imyinterface.Height = 3;//为派生类中的Height属性赋值76       Console.WriteLine("矩形的面积为:" + imyinterface.Area());77     }78   }79 }