Winforms,通过表单名称创建表单实例 [英] Winforms, create form instance by form name

查看:93
本文介绍了Winforms,通过表单名称创建表单实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个通过表单名称返回表单新实例的方法.这是我到目前为止的内容:

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)
    {
        return Assembly.GetExecutingAssembly().GetTypes().Where(a => a.BaseType == typeof(Form) && 
            a.Name == frmname).Cast<Form>().FirstOrDefault();
    }

但是,当我尝试执行此代码时出现以下错误:

However I get the following error when I attempt to execute this code:

无法将类型为"System.RuntimeType"的对象转换为类型为"System.Windows.Forms.Form".

此错误是什么意思?

推荐答案

您需要 Activator.CreateInstance 方法,该方法创建给定 Type :

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);
}

这篇关于Winforms,通过表单名称创建表单实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆