Winforms,通过窗体名称创建窗体实例

3
我需要一个按照表单名称返回新实例的方法。这是我目前已经拥有的代码:
```

我需要一个按照表单名称返回新实例的方法。这是我目前已经拥有的代码:

```
    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个回答

11

你需要使用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);
}

在我看来,你应该将其命名为“TryGetFormByName”,或者如果未找到类型,则抛出异常。(无论如何+1) - user743382

0
Assembly asm = typeof(EnterHereTypeInTheSameAssembly).Assembly;
Type type = asm.GetType(name);
Form form = (Form)Activator.CreateInstance(type);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接