是否可以在变量名的名称中使用变量号?
本文关键字:变量 变量名 是否 | 更新日期: 2023-09-27 18:18:53
(使用WPF)是否可以使用TextBox
的编号来选择参数名称?例如,用户可以将0、1、2或3作为文本放在TextBox
:
private void button1_Click(object sender, RoutedEventArgs e)
{
int test = int.Parse(textBox1.Text);
string nr1 = "this string is 1";
string nr2 = "this string is 2";
string nr3 = "this string is 3";
MessageBox.Show();
}
现在对于MessageBox.Show();
我想在nr(test)
中添加一些东西
这样的事情可能发生吗?
为什么不用字典呢?
var dict = new Dictionary<int,string>();
dict.Add(1,"String Number 1");
dict.Add(2,"String Number 2");
dict.Add(3,"String Number 3");
int test = int.Parse(textBox1.Text);
MessageBox.Show(dict[test]);
我想这会对你有帮助:
private void button1_Click(object sender, RoutedEventArgs e)
{
int test = int.Parse(textBox1.Text);
string[] nr = new string[3]{"this string is 1","this string is 2","this string is 3"};
MessageBox.Show(nr[test-1]);
}
您可以创建一个Dictionary<int,string>
,其中包含您想要通过键处理的所有数据:
MessageBox.Show(myDict[test])
在这里你可以看到MSDN文档
也可以使用FindName()
让我们这样建议:
XAML
<StackPanel>
<TextBox Height="23" Name="textBox1" Width="120" />
<TextBox Height="23" Name="textBox2" Width="120" />
<TextBox Height="23" Name="textBox3" Width="120" />
<Button Content="Button" Height="23" Width="75" Click="button1_Click" />
</StackPanel>
你可以像这样
private void button1_Click(object sender, RoutedEventArgs e)
{
int number =2;
TextBox tb = this.FindName(string.Format("textBox{0}", number)) as TextBox;
MessageBox.Show(tb.Text);
}
我建议你使用字典。处理字典可以简化你的生活。