我在C#中有四个文本框,如果任何文本框的值是:空字符串,那么它必须被指定为'0'.我已经尝试了下面的代码似乎是lenghty.
if (txtReset1.Text == "")
{
txtReset1.Text = "0";
}
if (txtReset2.Text == "")
{
txtReset2.Text = "0";
}
if (txtReset3.Text == "")
{
txtReset3.Text = "0";
}
if (txtReset4.Text == "")
{
txtReset4.Text = "0";
}
Run Code Online (Sandbox Code Playgroud)
是否有比上述更有效的代码?
而不是重复自己,创建一个新的方法来处理它:
private void SetEmptyTextBoxToZero(TextBox textBox)
{
if (textBox != null && string.IsNullOrEmpty(textBox.Text)
{
textBox.Text = "0";
}
}
Run Code Online (Sandbox Code Playgroud)
然后用以下代码替换代码:
SetEmptyTextBoxToZero(txtReset1);
SetEmptyTextBoxToZero(txtReset2);
SetEmptyTextBoxToZero(txtReset3);
SetEmptyTextBoxToZero(txtReset4);
Run Code Online (Sandbox Code Playgroud)
正如"Binkan Salaryman"所暗示的那样,如果你有很多需要以这种方式处理的文本框,那么你可以在列表中存储对它们的引用,然后迭代它们,而不是像上面那样列出它们:
var textBoxes = new List<TextBox> { txtReset1, txtReset2, txtReset3, txtReset4 };
...
// Option 1: using .ForEach()
textBoxes.ForEach(tb => SetEmptyTextBoxToZero(tb));
// Option 2: using foreach
foreach (var tb in textBoxes)
{
SetEmptyTextBoxToZero(tb);
}
Run Code Online (Sandbox Code Playgroud)