定義一個(gè)借口,接口封裝了矩形的長(zhǎng)和寬,而且還包含一個(gè)自定義的方法以計(jì)算矩形的面積。然后定義一個(gè)類,繼承自該接口,在該類中實(shí)現(xiàn)接口中自定義方法。
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 /// 長(zhǎng)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 /// 計(jì)算矩形面積28 /// </summary>29 int Area();//////// int Area(int Width, int Height); 30 }31 class PRogram : ImyInterface//繼承自接口32 {33 private int width = 0;34 private int height = 0;35 /// <summary>36 /// 長(zhǎng)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 /// 計(jì)算矩形面積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();//實(shí)例化Program類對(duì)象73 ImyInterface imyinterface = program;//使用派生類對(duì)象實(shí)例化接口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 /// 長(zhǎng)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 /// 計(jì)算矩形面積28 /// </summary>29 int Area();30 }31 class Program : ImyInterface//繼承自接口32 {33 int width = 0;34 int height = 0;35 /// <summary>36 /// 長(zhǎng)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 /// 計(jì)算矩形面積65 /// </summary>66 public int Area()67 {68 return Width * Height;69 }70 static void Main(string[] args)71 {72 Program program = new Program();//實(shí)例化Program類對(duì)象73 ImyInterface imyinterface = program;//使用派生類對(duì)象實(shí)例化接口ImyInterface74 imyinterface.Width = 5;//為派生類中的Width屬性賦值75 imyinterface.Height = 3;//為派生類中的Height屬性賦值76 Console.WriteLine("矩形的面積為:" + imyinterface.Area());77 }78 }79 }
本題的關(guān)鍵出錯(cuò)點(diǎn)是:在接口里聲明方法的時(shí)候的形式要與接口的實(shí)現(xiàn)里面方法的定義形式保持一致,否則會(huì)出現(xiàn)錯(cuò)誤:“
錯(cuò)誤 1 “Area”方法沒(méi)有任何重載采用“2”個(gè)參數(shù)”
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注