问题
Here is my Circle class code.
class Circle
{
private double radius;
private double area;
public Circle(double radius)
{
this.radius = radius;
}
public double Area
{
set { area = Math.PI * Math.Pow(radius, 2); }
get { return area; }
}
}
This is test code.
Circle circle1 = new Circle(3);
MessageBox.Show("Circle 1 Area: " + circle1.Area);
So for some reason, when I use the MessageBox.Show(), it seems to give me values of zero instead. I gave the circle a value of 3 so shouldn't my constructor set the value of the radius that?
回答1:
Because you haven't ever called the setter on Area. Perhaps you want something like this instead?
class Circle
{
private double radius;
public Circle(double radius)
{
this.radius = radius;
}
public double Area
{
get { return Math.PI * Math.Pow(radius, 2); }
}
}
This will compute the Area every time it is requested.
回答2:
Your Area
property should be:
public double Area
{
get { return Math.PI * Math.Pow(radius, 2); }
}
and you don't need the area
field.
回答3:
I'm not sure you need a set
in this instance (You didn't use it)
try
get { return Math.PI * Math.Pow(radius, 2); }
来源:https://stackoverflow.com/questions/19844974/why-am-i-getting-a-value-of-zero-for-my-circle