Winforms,通过表单名称获取表单实例

时间:2012-08-23 12:40:38

标签: c# winforms

我需要一个方法,通过表单的名称返回表单的新实例。以下是我到目前为止的情况:

    public Form GetFormByName(string frmname)
    {
        return Assembly.GetExecutingAssembly().GetTypes().Where(a => a.BaseType == typeof(Form) && 
            a.Name == frmname).Cast<Form>().FirstOrDefault();
    }

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

无法将“System.RuntimeType”类型的对象强制转换为“System.Windows.Forms.Form”。

这个错误是什么意思?

2 个答案:

答案 0 :(得分:10)

您需要Activator.CreateInstance方法创建一个给定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);
}

答案 1 :(得分:0)

Assembly asm = typeof(EnterHereTypeInTheSameAssembly).Assembly;
Type type = asm.GetType(name);
Form form = (Form)Activator.CreateInstance(type);
相关问题