我遇到了四个错误。
在用于打印形状区域的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;
}
}
}
答案 0 :(得分:1)
名称区域不存在,所以您不能使用它。 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;
}
答案 1 :(得分:0)
Microsoft文档提供了一个很好的示例,可以说明您通常在这里想要完成的工作: