4

这对我来说似乎一团糟,我的头脑告诉我必须有更好的方法。

我在网页上有 6 个控件。

if (printer_make_1.Text != "" && printer_model_1.Text != "" && printer_make_2.Text != "" && printer_model_2.Text != "" && printer_make_3.Text != "" && printer_model_3.Text != "")
{
  // Do something
}

最好/最有效的方法是什么?

4

7 回答 7

6

如果您想提高可读性或在其他地方使用相同的逻辑,您可以重构为方法:

public Boolean AllControlsHaveAValue() {
    return (printer_make_1.Text != ""
        && printer_model_1.Text != ""
        && printer_make_2.Text != ""
        && printer_model_2.Text != ""
        && printer_make_3.Text != ""
        && printer_model_3.Text != "");
}

然后问:

if (AllControlsHaveAValue()) {
    // do something
}
于 2012-04-27T15:49:23.353 回答
5

重组从您的数据开始:避免printer_make_1printer_make_2...

class PrinterData
{
   public string Make { get; set; }
   public string Model { get; set; }
}

PrinterData[] printers = new PrinterData[3];  //or use a List<>

printers[0] = new PrinterData { Make = "PH", Model = "1A" };
...

if (printers.All(p => ! (p.Make == "" || p.Model == "")) )
  ...
于 2012-04-27T15:51:37.997 回答
3
if(new[] { printer_make_1, printer_model_1 ...}.All(l => l.Text != string.Empty)
{
    //do something
}

您可能希望将其拆分为更具可读性:

var labels = new[] { printer_make_1, printer_model_1 ... };
if(labels.All(l => l.Text != string.Empty))
{
    //do something
}
于 2012-04-27T15:47:04.917 回答
2

我通常将该测试放入一个方法中并调用它以使 if 更易于阅读

private boolean AreAllPrinterFieldsFilled()
{
    return (printer_make_1.Text != "" 
        && printer_model_1.Text != "" 
        && printer_make_2.Text != "" 
        && printer_model_2.Text != "" 
        && printer_make_3.Text != "" 
        && printer_model_3.Text != "");
}

然后在if中:

if (AreAllPrinterFieldsFilled)
{
    // Do something
}
于 2012-04-27T15:49:40.663 回答
1

有很多方法可以做到这一点——没有一个是优雅的。做对您(以及可能落后于您的人)最易读的事情。

我可能会采用这种方法:

string makeText = String.Concat(printer_make_1.Text, printer_make_2.Text, printer_make_3.Text);
string modelText = String.Concat(printer_model_1.Text, printer_model_2.Text, printer_model_3.Text);

if (makeText.Length != 0 && modelText.Length != 0)
{
    // Do something
}
于 2012-04-27T15:49:41.257 回答
0
if (!Enumerable.Range(1, 3)
    .Any(i => ((TextBox)FindControl("printer_make_" + i)).Text == "" || 
        ((TextBox)FindControl("printer_model_" + i)).Text == "") {...}

它允许您稍后扩展打印机品牌和型号的数量,但不是强类型。

于 2012-04-27T15:50:44.970 回答
0
private bool CheckAllEmpty(params TextBox[] textBoxes)
{
    return textBoxes.All(tb => tb.Text != null);
}

private void Foo()
{
    ...

    if (CheckAllEmpty(tb1, tb2, tb3))
    {
        mbox("tb1, tb2 and tb3 are all empty");
    }
    else
    {
        mbox("tb1, tb2 or tb3 isn't empty");
    }

    ...
}
于 2012-04-27T15:57:00.540 回答