Home > Blockchain >  How to randomly create a form from a specified list of forms?
How to randomly create a form from a specified list of forms?

Time:06-07

I want to write a code that pops up a random form from a specified list of forms when a button is pressed in winforms.

The forms in the specified list include Form1, Form2, and Form3. It must not be created to a form other than the specified forms.

The code I'm using now works using switch() and if(). However, when increasing or decreasing the number of Forms, it is cumbersome to modify all kinds of places.

I know how to create the form.

private void ChangeForm(object sender, EventArgs e)
{
  var form = new Form1();
  form.ShowDialog();
}

The part I'm stuck on is that I'm not sure what to do when I use the new keyword to specify the form I want to create.

Any help would be appreciated.

CodePudding user response:

I would consider creating a list of Func<Form> and then selecting randomly from the list to create your Form. The advantage with a Func<Form> is that you can incorporate more complex initialization and the advantage with a List<> is that you can dynamically add more Form factories at run-time.

Something like this:

private Random _random = new Random();

private List<Func<Form>> _formFactories = new List<Func<Form>>()
{
    () => new Form2(),
    () => new Form3()
    {
        Text = "My Caption",
    },
    () => new Form4(),
}

private void ChangeForm(object sender, EventArgs e)
{
    var form = _formFactories[_random.Next(0, _formFactories.Count)].Invoke();
    form.ShowDialog();
}

CodePudding user response:

This can be solved using Activator.CreateInstance(Type type).

You only need to create a separate value for the type parameter.

The reason for creating a random object in a field is to ensure randomness by creating it only once.

public partial class Form1 : Form
{
    private Random random = new Random();

    public Form1()
    {
        InitializeComponent();
    }

    private void ShowDialogRandomForm(object sender, EventArgs e)
    {
        var formsType = CreateFormsType();
        var randomNumber = random.Next(0, formsType.Length);
        var randomFormType = formsType[randomNumber];
        var randomForm = Activator.CreateInstance(randomFormType) as Form;

        randomForm?.ShowDialog();
    }

    private Type[] CreateFormsType()
    {
        return new[] { typeof(Form1), typeof(Form2), typeof(Form3) };
    }
}

If you want to change the specified list of forms, you only need to modify the CreateFormsType() method.

  • Related