如何打开一个方法的形式,如果通过了名作为参数 [英] How do I open a form in a method if passed its name as a parameter
问题描述
我想创建一个标准方法来打开基于传递给它的参数表。基本上,要完成这件事:
I am trying to create a standard method to open a form based on the parameter passed to it. Basically, to get this done:
using (Quotes newQte = new Quotes())
{
newQte.ShowDialog();
}
替换:
Quotes with a passed parameter, e.g. FormToOpen.
这是在所有可能的?
Is this at all possible?
推荐答案
这是可能使用工厂方法的这样做。
It is possible using a "Factory Method" to do so.
您需要定义FormToOpen像这样(我重命名为的CreateForm()
为清楚起见):
You would define FormToOpen like this (I'm renaming it to createForm()
for clarity):
Func<Form> createForm;
所以,code会是这个样子:
So the code would look something like this:
private void MakeAndDisplayForm(Func<Form> createForm)
{
using (var form = createForm())
{
form.ShowDialog();
}
}
您会这样称呼它:
MakeAndDisplayForm(() => new MyForm());
其中, MyForm的
是要 MakeAndDisplayForm()
以创建。
这是相当常见的做这种事情;通常你通过生成器功能,以一类的构造函数。然后该类使用以后创建者函数来创建的东西,它可以使用,不知道他们是如何创建的。
It's fairly common to do this kind of thing; often you pass the creator function to the constructor of a class. Then that class uses the creator function later on to create things that it can use, without knowing how they were created.
这是 Depencency注射的一种形式。
(声明:所有错误检查省略为简洁起见的)
这篇关于如何打开一个方法的形式,如果通过了名作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!