[英]How Can I use switch statement instead of too many else if
Hello please help me out in writing switch statement for the below else if 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;
}
You could do something like this: 您可以执行以下操作:
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;
}
You might want to check for nulls though. 您可能需要检查是否为空。 This code assumes that none of the controls or the
.Text
properties are null. 此代码假定所有控件或
.Text
属性都不为空。
I'd approach this as follows: 我会这样处理:
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;
}
}
You can use Something like this: 您可以这样使用:
private bool IfTextBoxEmpty(string text, string message, Control control)
{
if (text == "")
{
MessageBox.Show(message);
this.ActiveControl = control;
return true;
}
return false;
}
And the Usage: 用法:
if (!IfTextBoxEmpty(ClientAddressTextBox.Text, "Please Enter Client Address", ClientAddressTextBox)
{
//if not - Do Something
}
This is a pseudo code for a switch statement. 这是switch语句的伪代码。
string statement;
switch(statement)
{
case (ClientAddressTextBox.Text == ""):
MessageBox.Show("Please Enter Client Address");
this.ActiveControl = ClientAddressTextBox;
break;
case (InnerpathTextBox.Text == ""):
...
}
and so on. 等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.