如何将数据类型(字符串)转换为类型(表单)

本文关键字:转换 类型 表单 字符串 数据类型 | 更新日期: 2023-09-27 17:54:19

我有一个存储在字符串变量中的表单名称,我想把这个字符串传递给采用form Type 的类

string Str = "MainForm";       // this is form name 
// I try to convert the data type string to form type like this
Form FormNm = (Form) Str ;
// there is the message appears cannot convert type 'sting'   to 'form'
TransLang.SaveControlsLanguage(FormNm);   // this is the class

感谢

如何将数据类型(字符串)转换为类型(表单)

string myType = "MyAssembly.MyType";
Assembly asm = Assembly.LoadFrom("MyAssembly.dll"); // creating instance by loading from other assembly
//Assembly asm = Assembly.GetExecutingAssembly();  // for creating instance from same assembly
//Assembly asm = Assembly.GetEntryAssembly(); // for creating instance from entry assembly
Type t = asm.GetType(myType);
Object obj = Activator.CreateInstance(t, null, null);

因为它是一个System.Windows.Form,如果你想显示你可以像一样做的表单

Form frm = obj as Form; // safely typecast
if (frm != null) // kewl it is of type Form
{
    //work with your form
    fmr.Show();
}
System.Reflection.Assembly.GetExecutingAssembly();
  Form frm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
  frm.Show();

将其添加到代码中。

不能直接将string转换为form。您应该创建一个新表单,并将表单的名称设置为相关字符串。

嗯,你基本上不能。可以定义自定义强制转换运算符,该运算符基于某些逻辑,给定指定的字符串,创建一个表单。但这将是非常灵活的解决方案。

相反,只需重新构建代码,并根据提供的字符串创建一个表单。例如:

//Dictionary of the string versus Forms
Dictionary<string,Form> data = new Dictionary<string,Form> {
   { "string1", new Form1()}, //different form type are associated
   { "string2", new Form2()}  // to different string keys
    .....
}; 
public Form GetForm(string value){    
   return data [value];
}

这只是一个想法,构建您所需要的东西。

您可以使用此代码,

System.Reflection.Assembly.GetExecutingAssembly();
Form newForm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
newForm.Show();`