3

我正在尝试创建一个标准方法来根据传递给它的参数打开表单。基本上,要完成这项工作:

using (Quotes newQte = new Quotes())
{
    newQte.ShowDialog();
}

通过替换:

Quotes with a passed parameter, e.g. FormToOpen.

这是可能吗?

4

2 回答 2

4

It is possible using a "Factory Method" to do so.

You would define FormToOpen like this (I'm renaming it to createForm() for clarity):

Func<Form> createForm;

So the code would look something like this:

private void MakeAndDisplayForm(Func<Form> createForm)
{
    using (var form = createForm())
    {
        form.ShowDialog();
    }
}

You would call it like this:

MakeAndDisplayForm(() => new MyForm());

Where MyForm is the type of form that you want MakeAndDisplayForm() to create.

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.

This is a form of Depencency Injection.

(Disclaimer: All error checking elided for brevity)

于 2013-05-19T21:54:10.080 回答
2

根据一个参数创建一个创建要显示的表单的方法:

public static Form CreateAppropriateForm(int formToOpen)
{
    switch (formToOpen) {
        case 0:
            return new Quotes();
        case 1:
            return new Citations();
        case 2:
            return new References();
        default:
            throw new ArgumentException("Invalid parameter value.");
    }
}

在哪里QuotesCitations并且References将是您的表单类,从Form.

然后,您可以在要显示表单时调用该方法:

using (Form form = CreateAppropriateForm(2)) {
    form.ShowDialog();
}

这里显示了值的示例2- 但您可以自由插入任何其他表达式,这些表达式会产生可用于您的表单选择方法的值。

Of course, you can also declare formToOpen in a more meaningful way, if that is suitable for your application. For example, you can declare it as a custom enum type, where each enum value denotes a particular form.

于 2013-05-19T21:50:35.523 回答