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

C# 如何将数据类型(字符串)转换为类型(表单),c#,winforms,C#,Winforms,我有一个存储在字符串变量中的表单名,我想把这个字符串传递给采用表单类型的类 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 'fo

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

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();
}

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

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

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

//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];
}
//字符串和表单的字典
字典数据=新字典{
{“string1”,new Form1()},//关联了不同的表单类型
{“string2”,新的Form2()}//到不同的字符串键
.....
}; 
公共窗体GetForm(字符串值){
返回数据[值];
}
这只是一个想法,架构师您真正需要的东西。

System.Reflection.Assembly.getExecutionGassembly();
Form frm=(Form)asm.CreateInstance(“WindowsFormsApplication1”);
frm.Show();
将此添加到您的代码中。

您可以使用此代码

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

对ans进行了更多更新!
System.Reflection.Assembly.GetExecutingAssembly();
Form newForm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
newForm.Show();`