[英]How to optimize this code?
当然,必须有很多方法来优化下面的代码,我必须确保很多文本框都不是空的,然后读取它们的值:
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()。
我将循环遍历这些TextBox所在的Controls集合,然后仅对TextBox进行过滤,并进行检查和连接。
我也强烈建议使用StringBuilder而不是+ =。
有很多方法可以重构这个。 您选择的方法取决于您的特定方案和需求。
这一切都只是我头脑中的东西。 如果你更多地工作,我相信你可以做得更好。 :)
(如果这是作业,请添加作业标签。)
编辑:
我不禁想知道UI的设计一般基于你在另一篇帖子中的评论,说明将字符串连接在一起需要“很多秒”。 10个字符串本身就是一个非常微不足道的时间,但这表明你的外部循环(即生成i
)运行时间相当长。
如果您处于可以自由做出此类决策的位置,您确定您的UI实际上对于手头的任务有用吗? 一般来说,大量文本框对是一个困难的用户界面。 也许ListView
更合适。 它会隐含地包含一个集合,因此您不必处理这个“十个文本框”的愚蠢,并且将是一个更容易的UI供您的用户一般遵循。
编写一个接受foo和bar类型的函数。 将所有foo1和bar1传递给foo10和bar10到函数以获取值。 你也可以创建foo和bar数组,你可以循环调用方法来获取字符串。
foreach (Control ctrl in Page.Controls) {
if (ctrl is TextBox) {
if (ctrl.Text.Length != 0) {
output.Text += myStrings[i] + "/" + ctrl.Text;
}
}
}
未经测试,但应该工作。 有了这个,您的文本框可以命名为任何东西。
你能把foo1-foo10变成一个数组,foo [10],同样吧吧? 这将允许您将其表达为一个简单的循环。
制作一个名为foo和bar的文本框的WebControl是否可行,它具有如下函数:
if (foo.Text.Length != 0 & bar.Text.Length != 0)
return myStrings[i] + " / " + foo.Text + " / " + bar.Text;
else
return string.Empty;
将十个这些放在您的页面上,然后使用:
output.Text = myControl1.FooBar + myControl2.FooBar + myControl3.FooBar + ...
(仍然有点混乱,但不是那么重复。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.