c# - 如何优化这段代码?

标签 c# optimization

肯定有很多方法可以优化以下代码,我基本上必须确保很多文本框不为空,然后读取它们的值:

if (foo1.Text.Length != 0 & bar1.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo1.Text + " / " + bar1.Text;
}

if (foo2.Text.Length != 0 & bar2.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo2.Text + " / " + bar2.Text;
}

if (foo3.Text.Length != 0 & bar3.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo3.Text + " / " + bar3.Text;
}

if (foo4.Text.Length != 0 & bar4.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo4.Text + " / " + bar4.Text;
}

if (foo5.Text.Length != 0 & bar5.Text.Length != 0) 
{
    output.Text += myStrings[i] + " / " + foo5.Text + " / " + bar5.Text;
}

if (foo6.Text.Length != 0 & bar6.Text.Length != 0)
    output.Text += myStrings[i] + " / " + foo6.Text + " / " + bar6.Text;

if (foo7.Text.Length != 0 & bar7.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo7.Text + " / " + bar7.Text;
}

if (foo8.Text.Length != 0 & bar8.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo8.Text + " / " + bar8.Text;
}

if (foo9.Text.Length != 0 & bar9.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo9.Text + " / " + bar9.Text;
}

if (foo10.Text.Length != 0 & bar10.Text.Length != 0)
{
    output.Text += myStrings[i] + " / " + foo10.Text + " / " + bar10.Text;
}

最佳答案

我会将重复的元素放在数组中,然后循环遍历它们。

TextBox[] foos = new TextBox[] { foo1, foo2, foo3, /* etc */ };
TextBox[] bars = new TextBox[] { bar1, bar2, bar3, /* etc */ };

for (int i = 0; i <= 10; i++)
    if (foos[i].Text.Length != 0 && bars[i].Text.Length != 0)
        output.Text += myStrings[i] + "/" + foos[i].Text + bars[i].Text;

当然,如果元素真的按顺序命名,您可以通过从表单的 Controls 集合中查找控件来填充数组,名称为“foo”+ number.ToString()。

关于c# - 如何优化这段代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/541903/

相关文章:

c# - 创建时无法解析 IMvxMainThreadDispatcher 类型的参数调度程序的参数

c# - File.Delete 尝试删除打开的文件失败但在进程退出时删除?

c++ - 为空间优化 tribools 数组

mongodb - Mongo 多对多

c# - HttpClient 静态与新

c# - 如何使用反射在 Winform 中托管 WPF 应用程序

c# - C#查询未返回任何内容

c++ - 是否为地址从未使用过的静态常量变量分配了内存?

algorithm - 这个问题对应于哪个背包问题变体?

r - 2 参数函数的优化