use*_*128 2 c# asp.net control-array
我正在编写一个C#/ ASP.Net Web应用程序,我有大量的文本框需要在后面的代码中设置为变量值.目前我正在做以下事情:
AspTextBox0.Text = codeBehindVariable[0];
AspTextBox1.Text = codeBehindVariable[1];
AspTextBox2.Text = codeBehindVariable[2];
AspTextBox3.Text = codeBehindVariable[3];
…
Run Code Online (Sandbox Code Playgroud)
有一个简单的方法可以在一个简单的"for"循环中执行此操作吗?
这是一个非常简化的示例,真实程序有一个开关案例和一些其他需要在分配变量时执行的测试.因此,"for"循环将极大地简化代码的编写和可维护性.回到VB6和控制阵列的旧时代,这是件小事.
VB6的美好时光早已过去,最好不要回来.
创建一个控制数组或更好的List<TextBox>自己:
var textBoxes = new List<TextBox> {
AspTextBox0,
AspTextBox1,
// ...
};
Run Code Online (Sandbox Code Playgroud)
然后,邮编用它codeBehindVariable:
textBoxes.Zip(codeBehindVariable,
(textBox, variable) => textBox.Text = variable);
Run Code Online (Sandbox Code Playgroud)
或者,如果您更喜欢for循环:
for ( int i = 0; i < codeBehindVariable.Length; i++ )
{
textBoxes[i].Text = codeBehindVariable[i];
}
Run Code Online (Sandbox Code Playgroud)
请记住,在for循环中,您必须确保两个textBoxes与codeBehindVariable具有相同数量的项目(或使循环运行仅在条目的最短列表的量).该Zip功能将自行处理.