Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在变量名上使用变量?_C# - Fatal编程技术网

C# 如何在变量名上使用变量?

C# 如何在变量名上使用变量?,c#,C#,此代码正在运行,但我想将其写入for循环中您可以使用字典 textBox12.Text = loto[1].ToString(); textBox11.Text = loto[2].ToString(); textBox10.Text = loto[3].ToString(); textBox9.Text = loto[4].ToString(); textBox8.Text = loto[5].ToString(); textBox7.Text = loto[6].ToString(); D

此代码正在运行,但我想将其写入for循环中

您可以使用字典

textBox12.Text = loto[1].ToString();
textBox11.Text = loto[2].ToString();
textBox10.Text = loto[3].ToString();
textBox9.Text = loto[4].ToString();
textBox8.Text = loto[5].ToString();
textBox7.Text = loto[6].ToString();
Dictionary Dictionary=newdictionary();
添加(1,文本框1);
... // 添加其他文本框
//通过索引访问字典
字典[f+11]=。。。

你不能。您必须将它们存储在字典列表中,并以这种方式访问它们。所以

  • 将控件添加到列表/字典
  • 在for循环中,按索引访问它们

在调用构造函数中看到的
InitialiseComponent()
之后,可以使用
列表
在构造函数中初始化它

以下是方法:

首先将a类
列表添加到您的表单中,如下所示:

Dictionary<int, TextBox> dictionary = new Dictionary<int, TextBox>();

dictionary.Add(1, textbox1);
... // add the other textboxes


// access the dictionary via index
dictionary[f+11] = ...
然后,当您想要访问文本框时,您可以这样做:

public Form1()
{
    // ...

    InitializeComponent();

    // ...

    textboxes.Add(textBox1);
    textboxes.Add(textBox2);
    textboxes.Add(textBox3);
    // ...etc up to however many text boxes you have.
}
for (int f = 1; f <= 6; ++f)
{
    textboxes[f+11].Text = loto[f].ToString(); // From your example.
}

for(int f=1;f我不确定您的TextBox控件是否已在表单中。如果没有,并且您希望动态创建TextBox控件,可以执行以下操作:

public Form1()
{
    // ...

    InitializeComponent();

    // ...

    textboxes.Add(textBox1);
    textboxes.Add(textBox2);
    textboxes.Add(textBox3);
    // ...etc up to however many text boxes you have.
}
for (int f = 1; f <= 6; ++f)
{
    textboxes[f+11].Text = loto[f].ToString(); // From your example.
}

for(int f=1;f什么是loto?显示所有相关的代码。什么确切的错误?我想这对我来说太高了。我在C上的级别是;我创建了Hello World窗口并创建了我的第一个应用程序:[link]
for (int f = 1; f <= 6; f++)
{
    Dictionary<int, TextBox> dict = new Dictionary<int, TextBox>();
    dict.Add(f, new TextBox());
    dict[f].Location = new Point(0, f * 20);
    dict[f].Text = loto[f].ToString();
    this.Controls.Add(dict[f]);
}