且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 C# 2010.NET 中创建控件数组?

更新时间:2023-12-06 11:53:46

该代码片段不会让您走得太远.创建控件数组没问题,只需在表单构造函数中初始化即可.然后您可以将其作为属性公开,尽管这通常是一个坏主意,因为您不想公开实现细节.像这样:

That code snippet isn't going to get you very far. Creating a control array is no problem, just initialize it in the form constructor. You can then expose it as a property, although that's generally a bad idea since you don't want to expose implementation details. Something like this:

public partial class Form1 : Form {
    private TextBox[] textBoxes;

    public Form1() {
        InitializeComponent();
        textBoxes = new TextBox[] { textBox1, textBox2, textBox3 };
    }

    public ICollection<TextBox> TextBoxes {
        get { return textBoxes; }
    }
}

然后让你写:

var form = new Form1();
form.TextBoxes[0].Text = "hello";
form.Show();

但不要让表单管理自己的文本框.

But don't, let the form manage its own text boxes.