在c#中从字符串调用表单
本文关键字:调用 表单 字符串 | 更新日期: 2023-09-27 17:49:15
我在c#中有一个Windows应用程序,我需要调用窗体,其名称在运行时保存为字符串变量。
;
我已经有了表单; Login.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)Assembly.GetExecutingAssembly().CreateInstance()
Form frm = (Form)Assembly.GetExecutingAssembly().CreateInstance("namespace.form");
frm.Show();