enum in constructor - how to?
I have a problem with this开发者_如何学JAVA exercise: Define a class that represent a circle. Constant defined class that holds the value of pi, and a variable defined in readonly holding the color of the circle. The possible colors are defined in enum. Variables defined class to hold the radius of the circle And functions that calculate the perimeter and area of the object. That's what I've done:
class Circle
{
public const double PI = 3.14;
public readonly enum color { Black, Yellow, Blue, Green };
int radius;
public Circle(string Color,int radius)
{
this.radius = radius;
}
}
I don't know how can I put the enum selection in the constructor. Thanks for helping.
public enum Color { Black, Yellow, Blue, Green };
class Circle
{
public const double PI = 3.14;
private Color _color;
int radius;
public Circle(int radius, Color color)
{
this.radius = radius;
this._color = color;
}
}
You can also pass string of color, but then you'll have to do Enum.Parse(type of enum, string value).
Just define your Enum outside of the class definition and declare a local read-only instance of the type.
enum Color
{
Black,
Yellow,
Blue,
Green
};
class Circle
{
public const double PI = 3.14;
public readonly Color color;
int radius;
public Circle(string colorValue, int r)
{
color = ( Color ) Enum.Parse( typeof( Color ), colorValue );
radius = r;
}
}
Try this:
public enum ColorEnum {
Black,
Yellow,
Blue,
Green
}
public class Circle {
public const double PI = System.Math.PI;
public ColorEnum Color;
public Circle(ColorEnum color,int radius)
{
this.radius = radius;
this.Color = color
}
}
An Enum is a type. When you declare an Enum, you are actually defining a new type within your program. Therefore, if you want to pass an Enum value in as a parameter, then you need to declare a parameter of that type.
You need to declare the enum
, and then use it as a variable type.
public enum Color { Black, Yellow, Blue, Green };
public readonly Color myColor;
try this code
public enum Color { Black, Yellow, Blue, Green };
class Circle
{
public const double PI = 3.14;
public readonly Color color;
int radius;
public Circle(Color color, int radius)
{
this.color = color;
this.radius = radius;
}
}
for use
Circle circle = new Circle(Color.Blue,100);
Use a private field and only expose the getter. I'd also make the enum a public class and pass it in directly:
class Circle
{
public const double PI = 3.14;
private Color _color;
int radius;
public Circle(Color Color,int radius)
{
_color = Color;
this.radius = radius;
}
public Color Color { return _color; }
}
public enum Color { Black, Yellow, Blue, Green }
what about the below
public enum Color
{
Black, Yellow, Blue, Green
}
class Circle
{
public const double PI = 3.14;
public Color Color { get; private set; }
int radius;
public Circle( int radius,Color color)
{
this.radius = radius;
this.Color = color;
}
}
精彩评论