我正在尝试编写一个游戏,并且正在使用枚举来存储油漆的颜色。枚举不断返回默认值,而不是字段的值。有没有办法防止这种情况?
这是一个 C# .NET Forms 应用程序,适用于 .NET Framework 4.6.1。
这是我的代码:
public enum PaintColor
{
Red,
Orange,
Yellow,
Green,
Blue
}
class Form1 : Form
{
private void Form1_Load(Object sender, EventArgs e)
{
PaintBucket orange = new PaintBucket()
{
Color = PaintColor.Orange,
Amount = 22
};
Label OrangeContent = new Label
{
Text = (orange.ToString()),
Width = 100,
Height = 20,
Top = 500,
Left = 500
};
Controls.Add(OrangeContent);
}
}
这是防御PaintBucket
类:
public class PaintBucket
{
public event EventHandler WriteToFile;
PaintColor color = PaintColor.Red;
int amount = 0;
public PaintBucket()
{
}
public PaintBucket(PaintColor col, int amnt)
{
this.Color = col;
this.Amount = amnt;
}
public PaintColor Color
{
get => color;
set{}
}
public int Amount
{
get => amount;
set{}
}
protected virtual void OnWriteToFile(EventArgs e)
{
WriteToFile(this, e);
}
public override string ToString()
{
return (this.Color.ToString() + ", " + this.Amount.ToString());
}
}
如上所示,字段orange
包含一个橙色PaintBucket
。标签OrangeContent
包含 orange.ToString
。但它显示为Red, 0
而不是Orange, 22
。红色是枚举的默认值,0 是整数的默认值。有没有办法返回字段的值而不是默认值?
更改属性以使用支持字段:
public PaintColor Color
{
get => color;
set => color = value;
}
public int Amount
{
get => amount;
set => amount = value;
}
或者使用自动实现的属性:
public PaintColor Color { get; set; } = PaintColor.Red;
public int Amount { get; set; } = 0;
您显式禁用了 setter ( set{}
),因此永远不会设置新值。构造函数代码this.Color = col;
什么都不做。
可以将属性定义为
public PaintColor Color { get; }
具有"仅构造函数可设置"属性。您将需要删除背线字段("颜色"),因为它不会被使用。
对于默认值:
public PaintColor Color { get; } = PaintColor.Red;