我需要一个方法,通过表单的名称返回表单的新实例。以下是我到目前为止的情况:
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”。
这个错误是什么意思?
答案 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);