从c#中的字符串调用表单

我在C#中有一个Windows应用程序,我需要调用一个Form,其名称在运行时保存为字符串变量。

喜欢;

我已经有了表格; Login.cs

string formToCall = "Login" Show(formToCall) 

这可能吗 ?

看看Activator.CreateInstance(String, String)

 Activator.CreateInstance("Namespace.Forms", "Login"); 

您还可以使用Assembly类(在System.Reflection命名空间中):

 Assembly.GetExecutingAssembly().CreateInstance("Login"); 

使用reflection:

 //note: this assumes all your forms are located in the namespace "MyForms" in the current assembly. string formToCall = "Login" var type = Type.GetType("MyForms." + formtocall); var form = Activator.CreateInstance(type) as Form; if (form != null) form.Show(); 

试试这个:

 var form = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(formToCall); form.Show(); 

为了更加动态,您可以将表单放在任何文件夹中:

 public static void OpenForm(string FormName) { var _formName = (from t in System.Reflection.Assembly.GetExecutingAssembly().GetTypes() where t.Name.Equals(FormName) select t.FullName).Single(); var _form = (Form)Activator.CreateInstance(Type.GetType(_formName)); if (_form != null) _form.Show(); } 

(表格)Assembly.GetExecutingAssembly()。的CreateInstance()

  Form frm = (Form)Assembly.GetExecutingAssembly().CreateInstance("namespace.form"); frm.Show();