我有一个存储在字符串变量中的表单名称,我想将此字符串传递给采用表单类型的类
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
谢谢
答案 0 :(得分:2)
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();
}
答案 1 :(得分:1)
System.Reflection.Assembly.GetExecutingAssembly();
Form frm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
frm.Show();
将此内容添加到您的代码中。
答案 2 :(得分:0)
您无法直接将string
转换为form
。您应该创建一个新表单并将表单的名称设置为相关的字符串。
答案 3 :(得分: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];
}
只是一个想法,架构你完全需要的东西。
答案 4 :(得分:0)
您可以使用此代码
System.Reflection.Assembly.GetExecutingAssembly();
Form newForm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
newForm.Show();`