C#方法通过字符串动态生成表单 [英] C# Method makes forms dynamically via string
问题描述
第一次在这里发帖,如果我在帖子中犯了任何错误,请告诉我,以便我可以修复它
所以我试图让类来处理大部分代码,我想做的一件事就是让一个人处理表单实例的所有打开和制作.在已经存在的实例上执行 .Show();
很简单,因为我知道它们的创建顺序我可以 Form _form = Application.OpenForms[i];
到抓住实例,但当它尚未创建时,我找不到处理它的方法,我读了一点,但找不到真正适合我想做的事情,一些关于反射的东西似乎是正确的路径,但无法使其正常工作,因此非常感谢您对此事的一些了解.
So I'm trying to make classes to handle most of the code, one of the things I wanted to do was to have one handle all the opening and making of form instances. Doing a .Show();
on instances that already exist was simple as I know the order they are created I can just Form _form = Application.OpenForms[i];
to grab the instance, but when it's not already created I couldn't find a way to deal with it, I read a bit unto it but couldn't find something that really fit what I wanted to do, something something about reflection seemed to be the right path but couldn't get it to work, so some light in the matter would be very appreciated.
简而言之,我正在尝试制作类似的东西:(我知道类似的事情是不可能的,但我认为这是准确解释我所寻求的东西的最简单方法.我提出的解决方法是让代码将每个表单生成到一个开关中并只发送它们的编号,所以这就是如果我找不到更好的解决方案,我会使用,但我想学习一种正确/更清洁"的方法来实现这一点)
In a nutshell I'm trying to make something like: (I know something similar is not possible but I think this is the easiest way to explain exactly what I seek. A workaround I made was to have the code to generate each of the Forms into a switch and just send their number, so it's what I'm gonna use if I can't find a better solution, but I wanted to learn a "proper/cleaner" way of achieving this)
static public bool MakeForm(string name)
{
name _name = new name();
_name.Show();
}
推荐答案
这是一个使用反射方法的简单示例:
Here's a simple example using the Reflection approach:
private void button1_Click(object sender, EventArgs e)
{
Form f2 = TryGetFormByName("Form2");
if (f2 != null)
{
f2.Show();
}
}
public Form TryGetFormByName(string formName)
{
var formType = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
.Where(T => (T.BaseType == typeof(Form)) && (T.Name == formName))
.FirstOrDefault();
return formType == null ? null : (Form)Activator.CreateInstance(formType);
}
这是检查表单是否已打开的替代版本:
Here's an alternate version that checks to see if the form is already open:
public Form TryGetFormByName(string formName)
{
// See if it's already open:
foreach (Form frm in Application.OpenForms)
{
if (frm.Name == formName)
{
return frm;
}
}
// It's not, so attempt to create one:
var formType = System.Reflection.Assembly.GetExecutingAssembly().GetTypes()
.Where(T => (T.BaseType == typeof(Form)) && (T.Name == formName))
.FirstOrDefault();
return formType == null ? null : (Form)Activator.CreateInstance(formType);
}
这篇关于C#方法通过字符串动态生成表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!