如何使用Dictionary在c#中的Method中存储值?

时间:2016-08-02 11:32:47

标签: c# dictionary

请帮我如何将这些值添加到字典中?我想删除整个switch语句并使用Dictionary而不是它来存储值并将int值返回给method。怎么办呢?

      private int ControlDecode(byte b)
    {

        int itype = -1;
        int ipacekttype = b & 0x0F;
        switch (ipacekttype)
        {
            case 0x01:
                if ((b & 0xF0) == 0x10 || (b & 0xF0) == 0x20 || (b & 0xF0) == 0x50 || (b & 0xF0) == 0x60)
                    itype = 0x11;
                break;
            case 0x02:
                if ((b & 0xF0) == 0x20 || (b & 0xF0) == 0x60 || (b & 0xF0) == 0x10 || (b & 0xF0) == 0x50)
                    itype = 0x12;
                break;
            case 0x03:
                if ((b & 0xF0) == 0x00 || (b & 0xF0) == 0x10 || (b & 0xF0) == 0x20 || (b & 0xF0) == 0x40 || (b & 0xF0) == 0x50 || (b & 0xF0) == 0x56)
                    itype = 0x13;
                break;
            case 0x04:
                if ((b & 0xF0) == 0x30 || (b & 0xF0) == 0x70)
                    itype = 0x14;
                break;
            case 0x05:
                if ((b & 0xF0) == 0x00 || (b & 0xF0) == 0x10 || (b & 0xF0) == 0x20 || (b & 0xF0) == 0x40 || (b & 0xF0) == 0x50 || (b & 0xF0) == 0x56)
                    itype = 0x15;
                break;
            case 0x06:
                if ((b & 0xF0) == 0x30 || (b & 0xF0) == 0x70)
                    itype = 0x16;
                break;
            case 0x08:
                    itype = 0x38;
                    break;
            case 0x09:
                    itype = 0x39;
                    break;
            case 0x0A:
                    itype = 0x3A;
                    break;
            case 0x0B:
                    itype = 0x3B;
                    break;
            case 0x0C:
                    itype = 0x3C;
                    break;
            default:
                break;
        }
        return itype;
    }

1 个答案:

答案 0 :(得分:2)

此函数将使用字典映射而不是switch语句返回相同的结果。

private int ControlDecode(byte b)
{
    int ipacekttype = b & 0x0F;
    if (ipacekttype >= 0x08 && ipacekttype <= 0x0C)
        return 0x30 + ipacekttype;

    var map = new Dictionary<int, int>
        {
            {0x11, 0x11 }, {0x21, 0x11 }, {0x51, 0x11 }, {0x61, 0x11 },
            {0x12, 0x12 }, {0x22, 0x12 }, {0x52, 0x12 }, {0x62, 0x12 },
            {0x03, 0x13 }, {0x13, 0x13 }, {0x23, 0x13 }, {0x43, 0x13 }, {0x53, 0x13 }, /*{0x56, 0x13 }, */
            {0x34, 0x14 }, {0x74, 0x14 },
            {0x05, 0x15 }, {0x15, 0x15 }, {0x25, 0x15 }, {0x45, 0x15 }, {0x55, 0x15 }, /*{0x56, 0x15 }, */
            {0x36, 0x16 }, {0x76, 0x16 },
        };

    return map.ContainsKey(b) ? map[b] : -1;
}

注意:您的逻辑中存在两个错误,我通过在地图中评论其值来强调这些错误。我的猜测是它是一个复制粘贴错误。它们应该分别由0x630x65替换。