Winforms, create form instance by form name

前端 未结 2 605
后悔当初
后悔当初 2020-12-19 21:51

I need a method that returns a new instance of a form by the name of the form. Here is what I have so far:

    public Form GetFormByName(string frmname)
             


        
2条回答
  •  囚心锁ツ
    2020-12-19 22:33

    You need the Activator.CreateInstance method which creates an instance of a type given a Type:

    public Form TryGetFormByName(string frmname)
    {
        var formType = Assembly.GetExecutingAssembly().GetTypes()
            .Where(a => a.BaseType == typeof(Form) && a.Name == frmname)
            .FirstOrDefault();
    
        if (formType == null) // If there is no form with the given frmname
            return null;
    
        return (Form)Activator.CreateInstance(formType);
    }
    

提交回复
热议问题