定義一個借口,接口封裝了矩形的長和寬,而且還包含一個自定義的方法以計算矩形的面積。然後定義一個類,繼承自該接口,在該類中實現接口中自定義方法。
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 Width 14 { 15 get; 16 set; 17 } 18 /// <summary> 19 /// 寬 20 /// </summary> 21 int Height 22 { 23 get; 24 set; 25 } 26 /// <summary> 27 /// 計算矩形面積 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 /// 長 37 /// </summary> 38 public int Width 39 { 40 get 41 { 42 return width; 43 } 44 set 45 { 46 width = value; 47 } 48 } 49 /// <summary> 50 /// 寬 51 /// </summary> 52 public int Height 53 { 54 get 55 { 56 return height; 57 } 58 set 59 { 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;//使用派生類對象實例化接口ImyInterface 74 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 Width
14 {
15 get;
16 set;
17 }
18 /// <summary>
19 /// 寬
20 /// </summary>
21 int Height
22 {
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 Width
39 {
40 get
41 {
42 return width;
43 }
44 set
45 {
46 width = value;
47 }
48 }
49 /// <summary>
50 /// 寬
51 /// </summary>
52 public int Height
53 {
54 get
55 {
56 return height;
57 }
58 set
59 {
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;//使用派生類對象實例化接口ImyInterface
74 imyinterface.Width = 5;//為派生類中的Width屬性賦值
75 imyinterface.Height = 3;//為派生類中的Height屬性賦值
76 Console.WriteLine("矩形的面積為:" + imyinterface.Area());
77 }
78 }
79 }
本題的關鍵出錯點是:在接口裡聲明方法的時候的形式要與接口的實現裡面方法的定義形式保持一致,否則會出現錯誤:“
錯誤 1 “Area”方法沒有任何重載采用“2”個參數”