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

stringを直接に変換することはできませんform。新しいフォームを作成し、フォームの名前を関連する文字列に設定する必要があります。

于 2013-01-19T08:48:33.057 に答える
0

このコードを使用できます。

System.Reflection.Assembly.GetExecutingAssembly();
Form newForm = (Form)asm.CreateInstance("WindowsFormsApplication1.<string>");
newForm.Show();`
于 2013-01-19T10:07:52.707 に答える
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 に答える