如何在 C# 中最小化 if 到 for

发布于 2024-10-06 08:28:37 字数 287 浏览 2 评论 0原文

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

就像

if(ddlname.SelectedIndex = 0)
{
//do this
}
else
{
//do this
}

if (txtprice.Text ="")
{
//do tis
}
else
{
//do this
}

我的整个程序由于这个而显得笨拙且不必要的长。我有大约 20 个下拉列表和 10 个文本框。有没有办法让它像 1 或 2 个 for 循环一样简单?

I have a set of codes in my function with a lot of if-else loops but each doing a diffrent one

like

if(ddlname.SelectedIndex = 0)
{
//do this
}
else
{
//do this
}

if (txtprice.Text ="")
{
//do tis
}
else
{
//do this
}

my whole program looks clumsy and unnecessarily long because of this one. I have some 20 dropdownlists and ten textboxes. Is there way to make this as simple as 1 or 2 for loops ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情深缘浅 2024-10-13 08:28:37

我目前正在阅读 Robert C. Martin 的《干净的代码》。根据他的书,你应该将你的方法重构为几个更小的方法,只做一件事。例如,您应该将每个执行操作提取到其自己的方法中。

至于你的问题,我认为没有任何方法可以使用 for 循环实现相同的逻辑,除非你对每个调用都执行相同的操作。

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
  }
}

I am currently reading Clean Code by Robert C. Martin. According to his book, you should refactor your method into several smaller methods, doing exactly one thing. You should for example extract every do this into its own method.

As to your question, I don't think there is any way of achieving the same logic using for loops, unless you do the same for every call.

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
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文