如何以编程方式实例化对象



我想从代码中实例化设计中的一些标签。我不想为每个文本框制作 50 个标签。就像 Unity 一样,我想在设计中多次实例化某个对象。如何在 c# 的 Visual Studio 中做到这一点。

您必须动态创建标签对象,例如:

int n = 4; // label counts
private void btnShow_Click(object sender, EventArgs e)
{
Label[] labels = new Label[n];
for (int i = 0; i < n; i++)
{        
labels[i] = new Label();
// Here you can modify the value of the label which is at labels[i]
}
// add labels to Controls container
for (int i = 0; i < n; i++)
{
this.Controls.Add(labels[i]);
}

最新更新