3

我有一个存储在字符串变量中的表单名称,我想将此字符串传递给采用表单类型的类

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

谢谢

4

5 回答 5

3
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();
}
于 2013-01-19T08:47:59.640 回答
2
System.Reflection.Assembly.GetExecutingAssembly();
  Form frm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
  frm.Show();

将此添加到您的代码中。

于 2013-01-19T08:57:56.503 回答
0

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

于 2013-01-19T08:48:33.057 回答
0

好吧,你基本上不能。您可以做的是定义自定义转换运算符,它基于一些逻辑,给定指定的字符串,创建一个表单。但这将是非常有线的解决方案。

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

//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];
}

只是一个想法,构建你真正需要的东西。

于 2013-01-19T08:51:53.023 回答
0

您可以使用此代码,

System.Reflection.Assembly.GetExecutingAssembly();
Form newForm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
newForm.Show();`
于 2013-01-19T10:07:52.707 回答