如何使用字符串显示对话框(表单) [英] How to show a dialog (Form) using string

查看:90
本文介绍了如何使用字符串显示对话框(表单)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,



任何人都可以帮助我。

我正在寻找打开对话框的解决方案:xyz.show (这)通过使用包含名称的字符串使其更灵活。

我尝试使用Type.GetType(xyz),但它只能在没有附加参数(this)的情况下工作。 br />


非常感谢提前。

解决方案

请尝试以下代码:

< pre lang =c#> private void LoadNewForm( string formName)
{
汇编汇编 = Assembly.GetExecutingAssembly();
Form myForm = assembly .CreateInstance(formName) as Form;
myForm.Show( this );
}



[根据SA的建议更新]

请注意,这将尝试从当前程序集实例化表单,可能不是这种情况。如果你想制作一些插件功能(你不想使用标准的插件框架,如 MEF或MAF [ ^ 由于某种原因),您还可以在运行时加载程序集。请参阅:使用Reflection在C#中运行时加载未引用的程序集 [ ^ ]。



这也有效,你不需要知道装配。

  private   void  LoadNewForm( string  formName)
{
类型t = Type.GetType(formName);
Form frm = Activator.CreateInstance(t) as Form;
frm.Show( this );
}



在这两种情况下你都必须传递 type 形式的完全限定名。

如果您想要获取表单的现有实例,那么这是另一个主题。


Hello friends,

may anyone can help me.
I am looking for a solution to open a dialog: xyz.show(this) by using a string that contains the name to make it more flexible.
I tried with Type.GetType("xyz"), but it works only without the additional parameter (this).

Many thanks in advance.

解决方案

Try following code:

private void LoadNewForm(string formName)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Form myForm = assembly.CreateInstance(formName) as Form;
myForm.Show(this);
} 


[updates based on SA''s suggestion]
Note that this will try to instantiate the form from the current assembly, which might not be the case. If you want to make some plugin feature (and you don''t want to use standard plugin frameworks like MEF or MAF[^] for some reason), you can also load assembly at runtime. Please see: Using Reflection to load unreferenced assemblies at runtime in C#[^].

This works too, and you do not need to know the assembly.

private void LoadNewForm(string formName)
{
Type t = Type.GetType(formName);
Form frm = Activator.CreateInstance(t) as Form;
frm.Show(this);
} 


You have to pass the fully qualified name of the form type in both cases.
It is an other topic if you want to grab an existing instance of the form.


这篇关于如何使用字符串显示对话框(表单)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆