![](/img/trans.png)
[英]Creating a C# program that calculates sum of the individual digits of a given number
[英]Creating a program that calculates area
我遇到了四個錯誤。
在用於打印形狀區域的WriteLine塊中,變量“ area”出現的兩個位置均給出錯誤消息:“名稱“ area”在當前上下文中不存在”。 第二個問題是在Rectangle類中:'ComputeArea'的GeometricFigure,錯誤顯示為''Rectangle.ComputeArea()'隱藏繼承的成員'GeometricFigure.ComputeArea()'。如果打算隱藏,請使用new關鍵字。” 最后一個錯誤是在Triangle:GeometricFigure類中,並且涉及“ public Triangle(int x,int y)”表達式中的“ Triangle”。 錯誤消息顯示為“'Rectangle.ComputeArea()'隱藏繼承的成員'GeometricFigure.ComputeArea()'。如果打算隱藏,請使用new關鍵字。
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}" + "\n\n" + "Computed Triangle is: {1}" + "\n",
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()方法無權訪問區域。 我認為您正在嘗試做的是:
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}" + "\n\n" + "Computed Triangle is: {1}" + "\n",
squ.Area, tri.Area);
Console.ReadLine();
}
}
但是,您也面臨更大的設計問題。 使用GeometricFigure基類將給您帶來很多問題。 我會完全使用它或使用接口代替。 另外,您的Triangle必須是:
public Triangle(decimal sideA, decimal sideB) : base(sideA, sideA)
{
this.Width = sideA;
this.Height = sideB;
}
Microsoft文檔提供了一個很好的示例,您可以嘗試在這里完成什么,通常您希望:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.