替代这个if语句

时间:2018-06-05 11:47:19

标签: c#

这看起来很明显,我目前使用的if语句在当前上下文中并不是非常有用。多个语句可以为true并且需要运行(可以选择多个复选框)。我可以重写它以在语句中包含所有可能的组合,但这似乎并不高效。我是否需要使用其他类型的语句,例如交换机?

   if (objFileAAGFlags.LocationStandard == true)
    {
        cbxLocationStandard.Checked = true;
        cbxLocationInsideM25.Checked = false;
        cbxLocationNorthScotland.Checked = false;
        cbxLocationNorthernIreland.Checked = false;
    }
    else if (objFileAAGFlags.LocationInsideM25 == true)
        {
            cbxLocationStandard.Checked = false;
            cbxLocationInsideM25.Checked = true;
            cbxLocationNorthScotland.Checked = false;
            cbxLocationNorthernIreland.Checked = false;
        }
    else if (objFileAAGFlags.LocationNorthScotland == true)
    {
        cbxLocationStandard.Checked = false;
        cbxLocationInsideM25.Checked = false;
        cbxLocationNorthScotland.Checked = true;
        cbxLocationNorthernIreland.Checked = false;
    }
    else if (objFileAAGFlags.LocationNorthernIreland == true)
    {
        cbxLocationStandard.Checked = false;
        cbxLocationInsideM25.Checked = false;
        cbxLocationNorthScotland.Checked = false;
        cbxLocationNorthernIreland.Checked = true;
    }
    else
    {
        cbxLocationStandard.Checked = false;
        cbxLocationInsideM25.Checked = false;
        cbxLocationNorthScotland.Checked = false;
        cbxLocationNorthernIreland.Checked = false;
    }

3 个答案:

答案 0 :(得分:3)

你去吧

cbxLocationStandard.Checked = objFileAAGFlags.LocationStandard == true;
cbxLocationInsideM25.Checked = objFileAAGFlags.LocationInsideM25 == true;
cbxLocationNorthScotland.Checked = objFileAAGFlags.LocationNorthScotland == true;
cbxLocationNorthernIreland.Checked = objFileAAGFlags.LocationNorthernIreland == true;

答案 1 :(得分:0)

你可以这样做:

        cbxLocationStandard.Checked = false;
        cbxLocationInsideM25.Checked = false;
        cbxLocationNorthScotland.Checked = false;
        cbxLocationNorthernIreland.Checked = false;

在开始时,而不是在每个内部,如果只是做:

   if (objFileAAGFlags.LocationInsideM25)
        {
            cbxLocationInsideM25.Checked = true;
        }

这是使其工作所需的最小代码更改,但是因为有多个选项可用,您可以直接将它们对齐:

 cbxLocationInsideM25.Checked = objFileAAGFlags.LocationInsideM25

每个旗帜。

答案 2 :(得分:0)

您说可以同时选中多个复选框,因此您可以删除所有if语句,只需从标记本身中分配值:

cbxLocationStandard.Checked = objFileAAGFlags.LocationStandard;
cbxLocationInsideM25.Checked = objFileAAGFlags.LocationInsideM25;
cbxLocationNorthScotland.Checked = objFileAAGFlags.LocationNorthScotland;
cbxLocationNorthernIreland.Checked = objFileAAGFlags.LocationNorthernIreland;

注意:如果任何属性为bool?,则必须执行以下操作:

cbxLocationStandard.Checked = objFileAAGFlags.LocationStandard == true;
// OR
cbxLocationStandard.Checked = objFileAAGFlags.LocationStandard.GetValueOrDefault();