Enum.ToString() 正在返回默认值而不是指定值

Enum.ToString() is returning default value instead of specified value

我正在尝试编写一个游戏,我正在使用一个枚举来存储油漆的颜色。 枚举保留 returning 默认值而不是字段的值。有什么办法可以避免这种情况吗?

这是一个适用于 .NET Framework 4.6.1 的 C# .NET Forms 应用程序。

这是我的代码:

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 class:

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 是整数的默认值。有没有办法 return 字段的值而不是默认值?

更改您的属性以使用支持字段:

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; }

有一个"constructor-settable only"属性。您将需要删除后场 ("color"),因为它不会被使用。

对于默认值:

public PaintColor Color { get; } = PaintColor.Red;