定义一个借口,接口封装了矩形的长和宽,而且还包含一个自定义的方法以计算矩形的面积。然后定义一个类,继承自该接口,在该类中实现接口中自定义方法。 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 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 }
时间: 2024-11-03 21:12:54