c#代码改进(数组,列表)

时间:2013-08-02 20:30:48

标签: c#

我想知道是否有人可以帮助我改进我的代码(?)

三周前,我决定学习C#/ C ++(决定从c#开始)并且我正在尽我所能,但我在理解一些基础知识方面遇到了问题 - 例如数组。

我想通过点击按钮添加“x”文本框(其中“x”是numericUpDown的值)。

我找到了一个解决方法如何做到这一点,但我有这种感觉,可以用不同的(更好的)方式编写它(我假设高级程序员会使用列表或数组)。

如果我错了,请原谅我,正如我之前提到的那样 - 我是新人并且尽力学习。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{

    if (numericUpDown1.Value == 1)
    {
        txtbx1.AutoSize = true;
        Controls.Add(txtbx1);
        txtbx1.Location = new Point(70, 100);
    }
    else if (numericUpDown1.Value == 2)
    {
        txtbx1.AutoSize = true;
        Controls.Add(txtbx1);
        txtbx1.Location = new Point(70, 100);

        txtbx2.AutoSize = true;
        Controls.Add(txtbx2);
        txtbx2.Location = new Point(70, 130);
    }
    else if (numericUpDown1.Value == 3)
    {
        txtbx1.AutoSize = true;
        Controls.Add(txtbx1);
        txtbx1.Location = new Point(70, 100);

        txtbx2.AutoSize = true;
        Controls.Add(txtbx2);
        txtbx2.Location = new Point(70, 130);

        txtx3.AutoSize = true;
        Controls.Add(txtbx3);
        txtbx3.Location = new Point(70, 160);
    }
}

3 个答案:

答案 0 :(得分:6)

不要重复自己,你可以这么简单地做到这一点:

private void button1_Click(object sender, EventArgs e)
{

    int y = 100;
    int x = 70;
    for (int i = 0; i < numericUpDown1.Value; i++)
    {
        var txtbx = new TextBox();
        txtbx.AutoSize = true;
        Controls.Add(txtbx);
        txtbx.Location = new Point(x, y);

        // Increase the y-position for next textbox.
        y += 30;
    }
}

答案 1 :(得分:5)

您可以随时创建TextBox控件,而不是预先创建// This is optional - in case you want to save these for use later. List<TextBox> newTextBoxes = new List<TextBox>(); private void button1_Click(object sender, EventArgs e) { int y = 100; for (int i=0;i<numericUpDown1.Value;++i) { TextBox newBox = new TextBox { AutoSize = true, Location = new Point(70, y) }; y += 30; Controls.Add(newBox); // This saves these for later, if required newTextBoxes.Add(newBox); } } 控件:

{{1}}

答案 2 :(得分:0)

你可以做两件事之一。第一种是使用switch语句,或者我的偏好是使用循环,尽管使用gui时这会有点棘手。像这样:

for (int i = 0; i < numericUpDown1.Value; i++)
    {
        //Make an TextBox Array or instantiate a new TextBox each iteration
            //and set properties here
    }

但正如我所说,如果你在循环中执行这些文本框的位置可能会有点棘手,所以使用switch语句会更容易。它们使用相对简单,但如果您遇到任何问题,请告诉我们。

另外,关于代码的注释,给文本框和其他GUI元素有意义的名称;我知道设计师会自动为它们分配名称,现在它不是问题,但在处理许多元素时会变得非常混乱。