引用、访问数据字典

Referencing, accessing a dictionary for data

我的程序使用 LibUSB 与 USB 设备通信,该设备具有按钮和 LED,用于向设备发送信息并从设备读取信息。通信是在字节数组中完成的,最多 1024 长,但几乎只有前 8 个字节很重要。读取时,我们读取字节数组,我想显示按下了哪个按钮或点亮了哪个LED。所以,我认为字典是最好的解决方案——按钮或 LED 名称的字符串值,键的字节数组。或者可能是相反的;字符串是键,数组是值。

public class DeviceInput
    {
        public static byte[] PowerArray = { 1, 0, 0, 16, 0, 0, 0, 0 };
        public string Name { get; set; }
        public byte[] InputArray { get; set; }
        public byte[] LEDArray { get; set; }


        public DeviceInput(string name, byte[] input, byte[] led)
        {
            Name = name;
            InputArray = input;
            LEDArray = led;
        }

        public static Dictionary<byte[], string> InputDictionary()
        {
            var dict = new Dictionary<byte[], string>();
            dict.Add(PowerArray, "Power Button");

            return dict;
        }

    }

在我的主程序中:

public Dictionary<byte[], string> inputDict = DeviceInput.InputDictionary();

并且在我的读取方法中,我获取读入的字节数组并将前 8 个字节存储到本地数组中,我使用 .ContainsKey() 查看 Dictionary 是否包含键(字节数组),然后会向用户显示值(字符串)。

byte[] data = 
{ 
    readBuffer[0], readBuffer[1], readBuffer[2], readBuffer[3],
    readBuffer[4], readBuffer[5], readBuffer[6], readBuffer[7]
};

if (inputDict.ContainsKey(data))
{
    Console.WriteLine("You pressed: " + inputDict[data]);
}

设备的 readBuffer 工作得很好,数组被完美填充,并且与我创建的字节数组 (PowerArray) 完全相同,所以我不确定 ContainsKey 为什么不是在职的。即使我将词典切换到 <string, byte[]> 并尝试 ContainsValue 而不是 ContainsKey,但没有成功。

字典是获取这些数据的最佳方式吗?我应该以不同的方式加载数据吗?我访问不正确吗?感谢您的指导。

这将解决您的问题(类似于@juharr 的建议)

class PowerArrayEqualityComparer : IEqualityComparer<byte[]>
{
    public bool Equals(byte[] x, byte[] y)
    {
        return x.SequenceEqual(y);
    }

    public int GetHashCode(byte[] obj)
    {
        return obj.Aggregate(0, (current, b) => current ^ b);
    }
}

您将以这种形式使用您的词典:

        Dictionary<byte[], string> myDict = 
            new Dictionary<byte[], string>(new PowerArrayEqualityComparer());

或者像这样初始化:

        var d = new Dictionary<byte[], string>(new PowerArrayEqualityComparer())
        {
            {new byte[] {0, 1, 2, 3}, "Button1"},
            {new byte[] {1, 1, 2, 3}, "Button2"}
        };

唯一不同的是在字典的构造函数中包含了 PowerArrayEqualityComparer class - 像这样 new PowerArrayEqualityComparer(),请确保在初始化字典时它就在那里。

只有这样,您才能将 byte[] 用作词典的 TKey

所以,下面的代码从那时起就可以正常工作了:

        var b = new byte[] {1, 1, 2, 3};
        Debug.WriteLine(d.ContainsKey(b));  

它会输出True.