我的课程之一是返回错误的值

时间:2018-09-30 19:56:34

标签: c#

我正在使用C#。

我总共有9节课。

3个类是抽象类,其余的是具体类。

这些类中的每一个都应该返回Area和volume(对于三维形状)。

除多维数据集类(返回0)之外,所有类都工作正常。

我从使用变量更改为使用属性,但仍然得到0。

我的测试类如下:

Shape[] shapes =
        {
            new Sphere ("A sphere is a sphere", 10),
            new Cube ("A cube is a cube", 10),
            new Tetrahedron ("Tetrahedron is a tetra", 10),
            new Circle ("a circle is a circle", 10),
            new Triangle ("a triangle is a triangle", 10, 10),
            new Square ("a square is a square", 10),

        };
        foreach (Shape s in shapes)
        {
            Console.WriteLine ( s );
        }

我的多维数据集类如下:

class Cube : ThreeDimensionalShape
{
    private double side; //holds side value

    public Cube ()
    {

    }
    public Cube (string desc, double s )
        :base (desc)
    {
        Side = side;
    }

    public double Side
    {
        get
        {
            return side;
        }
        set
        {
            if (value < 0)
            {
                Console.WriteLine ( "Side of cube must be greater or equal to 0" );
            }
            else
            {
                side = value;
            }
        }
    }
    public override double Area
    {
        get
        {
            return 6 * ( side * side ); //return cube area
        }
    }
    public override double Volume
    {
        get
        {
            return System.Math.Pow (Side, 3);
        }
    }

}

我的输出如下:

A sphere is a sphere
Area = 314.159265358979
Volume = 523.598775598299

A cube is a cube
Area = 0
Volume = 0

Tetrahedron is a tetra
Area = 173.205080756888
Volume = 117.851130197758

a circle is a circle
Area = 314.159265358979

a triangle is a triangle
Area = 50

a square is a square
Area = 100

2 个答案:

答案 0 :(得分:1)

这是因为设置s属性时未使用构造函数参数Side,所以side的默认值为0。

构造函数中的参数名称为s

public Cube (string desc, double s )

在构造函数中使用side变量中的值设置构造函数中的Side属性时,该变量位于Cube中的字段中。

从以下位置在构造函数主体中调整行:

Side = side;

收件人:

Side = s;

答案 1 :(得分:0)

只影响s而不是多维数据集构造函数中的side