If statement 如何最小化if';c中的s到a#

If statement 如何最小化if';c中的s到a#,if-statement,c#-2.0,If Statement,C# 2.0,我的函数中有一组代码,有很多if-else循环,但每个循环都有不同的代码 像 由于这个原因,我的整个程序看起来很笨拙,而且过长。我有大约20个下拉列表和10个文本框。有没有办法让这个循环像1或2这样简单?我目前正在阅读。根据他的书,你应该将你的方法重构成几个更小的方法,只做一件事。例如,您应该将每项操作提取到自己的方法中 至于你的问题,我不认为有任何方法可以实现相同的逻辑使用循环,除非你做同样的每一个调用 foreach (ctl in page.ctls) { TextBox tempTe

我的函数中有一组代码,有很多if-else循环,但每个循环都有不同的代码

由于这个原因,我的整个程序看起来很笨拙,而且过长。我有大约20个下拉列表和10个文本框。有没有办法让这个循环像1或2这样简单?

我目前正在阅读。根据他的书,你应该将你的方法重构成几个更小的方法,只做一件事。例如,您应该将每项操作提取到自己的方法中

至于你的问题,我不认为有任何方法可以实现相同的逻辑使用循环,除非你做同样的每一个调用

foreach (ctl in page.ctls)
{
  TextBox tempTextBox = ctl as TextBox;
  if (tempTextBox != null)
  {
    doTheSameForEveryTextBox(tempTextBox)
  }

  DropDownList tempDropDownList as DropDownList; // not sure if this is the right Type...
  if (tempDropDownList != null)
  {
    doTheSameForEveryTextBox(tempDropDownList)
  }
}

void doTheSameForEveryTextBox(TextBox tempTextBox)
{
  if (tempTextBox.Text == "")
  {
    //TODO: implement your code here
  }
}

void doTheSameForEveryDropDownList(DropDownList tempDropDownList)
{
  if (tempDropDownList.SelectedIndex == 0)
  {
    //TODO: implement your code here
  }
}

如果else不是循环。我在code.foreach(page.ctls中的ctl)中没有看到for循环的迹象-我可以这样做吗?可以。但是你必须检查ctl的类型。文本框没有SelectedIndex,同样,DropDownList也没有文本属性。还有一个问题是,Clean Code book是专为c#编写的。如果它是如此有用,我也应该得到一个:]这就是我想要传达的。如果我可以为textbox编写for循环,为下拉列表编写另一个for循环,并实现您的代码,如………..foreach(page.ctls中的textbox){If(textbox.text=”“)在我的想法中,下拉列表也是如此。这在c#中可能吗?我编辑了我的答案。这应该会让你朝着正确的方向前进。as运算符尝试强制转换对象。如果失败,则引用null。
foreach (ctl in page.ctls)
{
  TextBox tempTextBox = ctl as TextBox;
  if (tempTextBox != null)
  {
    doTheSameForEveryTextBox(tempTextBox)
  }

  DropDownList tempDropDownList as DropDownList; // not sure if this is the right Type...
  if (tempDropDownList != null)
  {
    doTheSameForEveryTextBox(tempDropDownList)
  }
}

void doTheSameForEveryTextBox(TextBox tempTextBox)
{
  if (tempTextBox.Text == "")
  {
    //TODO: implement your code here
  }
}

void doTheSameForEveryDropDownList(DropDownList tempDropDownList)
{
  if (tempDropDownList.SelectedIndex == 0)
  {
    //TODO: implement your code here
  }
}