C#:如何从另一个变量构造变量

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个案例的陈述.

dtb*_*dtb 7

如果已为每个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)

  • 您应该在ToDictionary之前添加.Where(t =>!string.IsNullOrEmpty(t.Name)),以防止捕获没有名称的TextBox并导致构建字典的异常. (2认同)

Bra*_*don 5

忽略您正在执行包含 500 个案例的 switch 语句这一事实,您可以使用 FindControl 方法,并将其转换为 TextBox。

((TextBox)FindControl("textbox_" + endingOfVariable)).Text = newValue;
Run Code Online (Sandbox Code Playgroud)