如何从字符串变量中调用表单名称 [英] how can call form name from string variable

查看:72
本文介绍了如何从字符串变量中调用表单名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从字符串变量中调用表单名称?

how can call form name from string variable?

推荐答案

您的问题根本不清楚,但我假设您想创建一个形式使用字符串.如果是这样:

Your question isn''t at all clear, but I''m assuming you want to create a form using a string. If that''s true:

var form = Activator.CreateInstance(Type.GetType("STRING_VARIABLE_HERE")).Unwrap() as Form;

if(form != null)
    form.Show();


除非您有充分的理由基于字符串激活类型(在这种情况下为表单),否则我强烈建议不要这样做.

使用字符串变量会使您的代码容易遭受各种错误,例如字符串中的拼写错误.编译器未检测到这些字符,因为表单名称在字符串中被隐藏".

就我个人而言,我宁愿重新考虑对此的需求,并可能使用泛型.例如,如果您需要所有表格都具有通用方法,则可以定义一个通用方法,该方法只接受任何Form,但仅接受Form.

有关泛型的信息,请参见 Visual Basic中的泛型类型 [ ^ ]
Unless you have a good reason to activate types (forms in this case) based on a string, I would strongly recommend not to do this.

Using a string variable makes your code vulnerable to different kinds of errors, for example spelling mistakes in the string. These are not detected by the compiler since the form name is ''hidden'' inside a string.

Personally I would prefer rethinking the need for this and possibly use generics instead. For example if you need to have a common method for all forms, you cound define a generic method that accepts any Form but only Form.

For information about generics, see Generic Types in Visual Basic[^]


嗨..

请尝试一下.

我在下面的应用程序中创建了两个表单. Form1和Form2.
在此应用程序中,WindowsFormsApplication2是我的命名空间.

在Form1中包含一个按钮,此按钮的单击事件将打开form2.
在Button中,单击事件看起来像..

Hi..

Please Try This.

I have create two form in my Application which is below.,
Form1 and Form2.
In this application WindowsFormsApplication2 is my namespace.

In Form1 contain one Button And this button''s click event i open form2.
In Button click event looks like..

var newForm = Activator.CreateInstance(Type.GetType("WindowsFormsApplication2.Form2")) as Form;

            if (newForm!= null)
                newForm.Show();


这篇关于如何从字符串变量中调用表单名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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