定义一个借口,接口封装了矩形的长和宽,而且还包含一个自定义的方法以计算矩形的面积。然后定义一个类,继承自该接口,在该类中实现接口中自定义方法。
1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Text;56namespaceTest067{8interfaceImyInterface9{10///<summary>11///长12///</summary>13intWidth14{15get;16set;17}18///<summary>19///宽20///</summary>21intHeight22{23get;24set;25}26///<summary>27///计算矩形面积28///</summary>29intArea();//////// int Area(int Width, int Height);30}31classPRogram : ImyInterface//继承自接口32{33privateintwidth =0;34privateintheight =0;35///<summary>36///长37///</summary>38publicintWidth39{40get41{42returnwidth;43}44set45{46width =value;47}48}49///<summary>50///宽51///</summary>52publicintHeight53{54get55{56returnheight;57}58set59{60height =value;61}62}63///<summary>64///计算矩形面积65///</summary>66publicintArea(intWidth,intHeight)67{68returnWidth *Height;69}70staticvoidMain(string[] args)71{72Program program =newProgram();//实例化Program类对象73ImyInterface imyinterface = program;//使用派生类对象实例化接口ImyInterface74imyinterface.Width =5;//为派生类中的Width属性赋值75imyinterface.Height =3;//为派生类中的Height属性赋值76Console.WriteLine("矩形的面积为:"+ imyinterface.Area(3,5));77}78}79}
下面是正确的:
1usingSystem;2usingSystem.Collections.Generic;3usingSystem.Linq;4usingSystem.Text;56namespaceTest067{8interfaceImyInterface9{10///<summary>11///长12///</summary>13intWidth14{15get;16set;17}18///<summary>19///宽20///</summary>21intHeight22{23get;24set;25}26///<summary>27///计算矩形面积28///</summary>29intArea();30}31classProgram : ImyInterface//继承自接口32{33intwidth =0;34intheight =0;35///<summary>36///长37///</summary>38publicintWidth39{40get41{42returnwidth;43}44set45{46width =value;47}48}49///<summary>50///宽51///</summary>52publicintHeight53{54get55{56returnheight;57}58set59{60height =value;61}62}63///<summary>64///计算矩形面积65///</summary>66publicintArea()67{68returnWidth *Height;69}70staticvoidMain(string[] args)71{72Program program =newProgram();//实例化Program类对象73ImyInterface imyinterface = program;//使用派生类对象实例化接口ImyInterface74imyinterface.Width =5;//为派生类中的Width属性赋值75imyinterface.Height =3;//为派生类中的Height属性赋值76Console.WriteLine("矩形的面积为:"+imyinterface.Area());77}78}79}
本题的关键出错点是:在接口里声明方法的时候的形式要与接口的实现里面方法的定义形式保持一致,否则会出现错误:“
错误 1 “Area”方法没有任何重载采用“2”个参数”