Creating a program that calculates area
我有四个我正在努力解决的错误。
在用于打印形状区域的写入行块中,变量"area"出现的两个位置都给出错误消息:"名称"area"在当前上下文中不存在"。第二个问题在类矩形中:"ComputeArea"的几何图形中,错误为"Rectangle.ComputeArea()"隐藏继承的成员"GeometricFigure.ComputeArea()"。如果有意隐藏,请使用new关键字。"最后一个错误在类triangle:geometricFigure中,并涉及"public triangle(int x,int y)"表达式中的"triangle"。错误消息为"rectangle.computerea()"隐藏继承的成员"geometricFigure.computerea()"。如果要隐藏,请使用新关键字。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; namespace ShapesDemo { class Program { static void Main(string[] args) { Rectangle rec = new Rectangle(8, 10); Square squ = new Square(11, 12); Triangle tri = new Triangle(10, 20); Console.WriteLine("Computed area is {0}" +" " +"Computed Triangle is: {1}" +" ", squ.ComputeArea(area), tri.ComputeArea(area)); } } abstract class GeometricFigure { public GeometricFigure(decimal sideA, decimal sideB) { this.height = sideA; this.width = sideB; } protected decimal area; protected decimal width; protected decimal height; public decimal Height { get { return height; } set { height = value; ComputeArea(); } } public decimal Width { get { return width; } set { width = value; } } public decimal Area { get { return area; } set { area = value; } } public void ComputeArea() { } } class Rectangle : GeometricFigure { public Rectangle(decimal sideA, decimal sideB) : base(sideA, sideB) { } public void ComputeArea() { area = width * height; WriteLine("The Area is" + width.ToString(), height.ToString()); } static void Display(Rectangle rec) { } } class Square : GeometricFigure { static void Display(Square squ) { } public Square(decimal sideA, decimal sideB) : base(sideA, sideA) { } } class Triangle : GeometricFigure { static void Display(Triangle tri) { } public Triangle(int x, int y) { this.Width = x; this.Height = y; } } |
}
名称区域不存在,因此无法使用。main()方法没有访问区域的权限。我想你想做的是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | class Program { static void Main(string[] args) { Rectangle rec = new Rectangle(8, 10); Square squ = new Square(11, 12); squ.ComputeArea(); Triangle tri = new Triangle(10, 20); tri.ComputeArea(); Console.WriteLine("Computed area is {0}" +" " +"Computed Triangle is: {1}" +" ", squ.Area, tri.Area); Console.ReadLine(); } } |
但你也有一个更大的设计问题。使用几何图形基类会给您带来很多问题。我可以完全使用它,或者使用一个接口。此外,三角形还需要:
1 2 3 4 5 | public Triangle(decimal sideA, decimal sideB) : base(sideA, sideA) { this.Width = sideA; this.Height = sideB; } |
Microsoft文档提供了一个很好的示例,说明您在这里试图完成的工作,通常您希望:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-define-abstract-properties-属性