ozz*_*TED 0 c# .net-3.5 winforms
如何在C#中构造新变量.
我的意思是,要像这样
public void updateXXX(string endingOfVariable, int newValue)
{
this.textBox_{endingOfVariable} = newValue;
}
Run Code Online (Sandbox Code Playgroud)
这是在Php中实现的:
$a = 'var'; $b = 'iable';
$variable = 'var';
echo ${$a.$b};
Run Code Online (Sandbox Code Playgroud)
但也许在C#中是可能的.
问题是 - 我在C#Windows窗体中创建了~500个文本框,如果我想设置一个值,我需要构建一个switch(){case:; 有500个案例的陈述.
如果已为每个TextBox指定了名称,则可以创建将名称映射到控件的字典:
var boxes = form.Controls.OfType<TextBox>().ToDictionary(t => t.Name);
public void Update(string name, int newValue)
{
boxes[name].Text = newValue.ToString();
}
Run Code Online (Sandbox Code Playgroud)
忽略您正在执行包含 500 个案例的 switch 语句这一事实,您可以使用 FindControl 方法,并将其转换为 TextBox。
((TextBox)FindControl("textbox_" + endingOfVariable)).Text = newValue;
Run Code Online (Sandbox Code Playgroud)