我有一个 C# 中的 Windows 应用程序,我需要调用一个表单,其名称在运行时保存到一个字符串变量中。
像;
我已经有了表格;登录.cs
string formToCall = "Login"
Show(formToCall)
这可能吗 ?
看看Activator.CreateInstance(String, String)
:
Activator.CreateInstance("Namespace.Forms", "Login");
您还可以使用Assembly
该类(在System.Reflection
命名空间中):
Assembly.GetExecutingAssembly().CreateInstance("Login");
使用反射:
//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();
要获得更多动态,您可以将表单放在任何文件夹中:
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();
}
试试这个:
var form = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(formToCall);
form.Show();
Form frm = (Form)Assembly.GetExecutingAssembly().CreateInstance("namespace.form");
frm.Show();