如果我如何使用switch语句而不是太多其他语句

时间:2016-03-14 13:01:29

标签: c# visual-studio-2015 switch-statement

你好请帮我写下面的if语句

的switch语句
if(ClientAddressTextBox.Text == "")
            {

                MessageBox.Show("Please Enter Client Address");
                this.ActiveControl = ClientAddressTextBox;
            }

            else if (InnerpathTextBox.Text == "")
            {
                MessageBox.Show("Please Enter Internal Path");
                this.ActiveControl = InnerpathTextBox;
            }

            else if (InspectorIDTextBox.Text == "")
            {
                MessageBox.Show("Please Enter Inspector ID");
                this.ActiveControl = InspectorIDTextBox;
            }

            else if (SerialNumberTextBox.Text == "")
            {

                MessageBox.Show("Please Enter Serial Number");
                this.ActiveControl = SerialNumberTextBox;
            }

4 个答案:

答案 0 :(得分:1)

你可以这样做:

var controls = new []
{
    new {Ctrl = InnerpathTextBox,     Error = "Please Enter Client Address"},
    new {Ctrl = ClientAddressTextBox, Error = "Please Enter Internal Path"},
    new {Ctrl = InspectorIDTextBox,   Error = "Please Enter Inspector ID"},
    new {Ctrl = SerialNumberTextBox,  Error = "Please Enter Serial Number"}
};

var firstToFailValidation = controls.FirstOrDefault(item => item.Ctrl.Text == "");

if (firstToFailValidation != null)
{
    MessageBox.Show(firstToFailValidation.Error);
    this.ActiveControl = firstToFailValidation.Ctrl;
}

您可能想要检查空值。此代码假定没有控件或.Text属性为空。

答案 1 :(得分:1)

我将按如下方式处理:

var validationMessages = new[]{new{Control = InnerpathTextBox, 
                                   Message = "Please Enter Internal Path"},
                               new{Control = InspectorIDTextBox, 
                                   Message = "Please Enter Inspector Id"},
                               //etc
};
foreach(var vm in validationMessages)
{
    if(string.IsNullOrWhiteSpace(vm.Control.Text))
    {
        MessageBox.Show(vm.Message);
        this.ActiveControl = vm.Control;
        break;
    }
}

答案 2 :(得分:0)

您可以使用以下内容:

<ul class="list-inline">

用法:

<ul class="list-unstyled">

答案 3 :(得分:-1)

这是switch语句的伪代码。

string statement;
switch(statement)
{
    case (ClientAddressTextBox.Text == ""):
    MessageBox.Show("Please Enter Client Address");
    this.ActiveControl = ClientAddressTextBox; 
    break;

    case (InnerpathTextBox.Text == ""):
    ...
}

等等。