创建许多相同的对象 C# Windows 表单

Creation of many identical objects C# Windows Forms

我需要通过单击按钮在 flowLayoutPanel 中创建一个与现有对象相同的对象。这样相同的属性仍然存在,但对象的名称发生了变化(例如,复制了 block1,新对象被称为 block2)。如何在 C# Windows Form 中完成?

我认为最好的方法是在您的控件中实施 IClonable。然后,您可以实施 Clone 方法,这将使您能够控制要克隆的属性。

public partial class MyUserControl : UserControl, ICloneable
{
    public string Name { get; set; }

    public MyUserControl()
    {
        InitializeComponent();
    }

    private void MyUserControl_Load(object sender, EventArgs e)
    {
        this.lblName.Text = this.Name;
    }

    public object Clone()
    {
        MyUserControl? result = Activator.CreateInstance(this.GetType()) as MyUserControl;

        if (result != null)
        {
            foreach (var control in this.Controls)
            {
                // Clone child controls or properties as needed
            }
        }

        return result ?? this;
    }
}

然后,在您的按钮点击事件中,您可以:

private void btnCreate_Click(object sender, EventArgs e)
{
    // Get the "master" control to clone from
    var userControl = this.flowLayoutPanel1.Controls[0] as MyUserControl;

    if (userControl != null)
    {
        for (int x = 2; x < 10; x++)
        {
            MyUserControl? clone = userControl.Clone() as MyUserControl;

            if (clone != null)
            {
                clone.Name = $"Block {x}";
                        
                this.flowLayoutPanel1.Controls.Add(clone);
            }
        }
    }
}