简体   繁体   中英

What can be done to shorten my if-else code?

Is there a way to shorten this C# code?

    byte[] temp = new byte[3];
    InventoryKeyItemID = LoadData_readbytes(offset + 0x5ED, 3, file);
    temp[0] = InventoryKeyItemID[0];
    if (temp[0] >= 128)
    {
        checkedListBox_Inventory_KeyItems.SetItemChecked(7, true);
        temp[0] -= 128;
    }
    if (temp[0] >= 64)
    {
        checkedListBox_Inventory_KeyItems.SetItemChecked(6, true);
        temp[0] -= 64;
    }
    if (temp[0] >= 32)
    {
        checkedListBox_Inventory_KeyItems.SetItemChecked(5, true);
        temp[0] -= 32;
    }
    if (temp[0] >= 16)
    {
        checkedListBox_Inventory_KeyItems.SetItemChecked(4, true);
        temp[0] -= 16;
    }
    if (temp[0] >= 8)
    {
        checkedListBox_Inventory_KeyItems.SetItemChecked(3, true);
        temp[0] -= 8;
    }
    if (temp[0] >= 4)
    {
        checkedListBox_Inventory_KeyItems.SetItemChecked(2, true);
        temp[0] -= 4;
    }
    if (temp[0] >= 2)
    {
        checkedListBox_Inventory_KeyItems.SetItemChecked(1, true);
        temp[0] -= 2;
    }
    if (temp[0] >= 1)
    {
        checkedListBox_Inventory_KeyItems.SetItemChecked(0, true);
    }

What this code does,

  1. Three bytes of data is read from a file then stored to InventoryKeyItemID array.
  2. The value of InventoryKeyItemID[0] is stored to temp[0].
  3. Checking the temp[0] variable using if-else statements to select what checkedListBox item would be checked.

You can use a for loop with some bit shifting:

for(int i = 7; i >= 0; i--)
{
  int number = 1 << i;

  if(temp[0] >= number)
  {
    checkedListBox_Inventory_KeyItems.SetItemChecked(i, true);
    temp[0] -= number;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM