.net 在数组索引中使用枚举值

8ftvxx2r  于 2023-02-26  发布在  .NET
关注(0)|答案(2)|浏览(138)

我有一个字节数组,其中一些数据存储在特定的索引中,我想把这些数据赋给标签,但是我目前的代码看起来很乱,我想用枚举来增加代码的可读性,但是问题是当我们用枚举作为数组索引时,我们需要把它们转换成整数,就像这样:* *[(int)enum. blabla]**。这会导致代码重复,而且看起来很糟糕。有没有办法把代码写得更干净?有人能帮我吗?
示例代码:

enum CarSpeeds
{
    CarBlue = 1,
    CarRed = 2,
    CarYellow = 3
}

byte[] myByte = new byte[size];

LabelCarBlueSpeed.Text = myByte[(int)CarSpeeds.CarBlue] + " km/h";
LabelCarBlueSpeed.Text = myByte[(int)CarSpeeds.CarRed] + " km/h";
LabelCarBlueSpeed.Text = myByte[(int)CarSpeeds.CarRed] + " km/h";

我们可以使用myByte[(int)CarSpeeds.CarRed],但必须使用**(int)**myByte[CarSpeeds.CarRed] + " km/h";

    • 编辑**:上一个例子中使用的"CarSpeeds"枚举只是为了便于说明和理解。我自己并不特别喜欢数组,但由于我从PLC读取数据,我需要使用字节数组(缓冲区)。我的目的是让我的代码更可读,仅此而已。
uajslkp6

uajslkp61#

请注意,枚举可以使用 * 任意 * 值,例如

enum CarSpeeds
    {
        CarSubZero = -123456789, // <- Negative value
        CarBlue = 1,
        CarRed = 2,
        CarYellow = 3, 
        // Hole at 4
        CarBlack = 5,
        CarInfinity = 1_000_000_000, // <- Very high value
    }

这就是为什么 array 不是最好的集合,你可以试试 dictionary(键类型为CarSpeeds):

using System.Linq;

...

// Create dictionary and initialize it as if it is an array:
// All keys are corresponding to default values
Dictionary<CarSpeeds, byte> myByte = Enum
  .GetValues<CarSpeeds>()
  .ToDictionary(key => key, key => default(byte));

...

myByte[CarSpeeds.CarSubZero] = 123;
myByte[CarSpeeds.CarInfinity] = 45;
yeotifhr

yeotifhr2#

更新一个类怎么样?

class Car
{
    private readonly Label _label;
    private int _speed;

    public Car(Label label, string color)
    {
        _label = label;
        Color = color;
    }

    public string Color { get; }
    public int Speed { get => _speed; set { _speed = value; _label.Text = value + " km/h"; } }
}

public MyView()
{
    InitializeComponent();
    _blueCar = new Car(LabelCarBlueSpeed, "blue"),
    _redCar = new Car(LabelCarRedSpeed, "red"),
    _yellowCar = new Car(LabelCarYellowSpeed, "yellow")
    _cars = new[] { _blueCar, _redCar, _yellowCar };
}

**更新:**从注解来看,它听起来更像是在解析数据缓冲区

class CarData
{
    private readonly byte[] _buffer;

    public CarData(byte[] buffer)
    {
        _buffer = buffer;
    }

    public byte BlueCarSpeed { get => _buffer[8]; set => _buffer[8] = value; }
    public byte RedCarSpeed { get => _buffer[10]; }
    public byte YellowCarSpeed { get => _buffer[12]; }
}

相关问题