将方法转换为泛型以便与Forms一起重用

时间:2016-03-14 10:18:21

标签: c# generics

我正在研究Excel的统计加载项,并且我必须为每个绘图实现以下方法。我有大约10个不同的图,每次只有Type的{​​{1}}更改。

Form

有没有办法让这个方法通用?类似下面的代码,但没有对private void ShowBoxWhiskerPlotForm() { // Check if the Form already exists. Create it if not. if (_boxWhiskerPlotForm == null || _boxWhiskerPlotForm.IsDisposed) _boxWhiskerPlotForm = new Forms.BoxWhiskerPlotForm(); // Check if the Form is already visible. if (_boxWhiskerPlotForm.Visible == false) // Show the Form if it isn't. _boxWhiskerPlotForm.Show( new WindowImplementation(new IntPtr(Globals.ThisAddIn.Application.Windows[1].Hwnd))); else // Refresh if it is. _boxWhiskerPlotForm.Refresh(); // Bring the Form to the front. _boxWhiskerPlotForm.BringToFront(); } 进行硬调用。这里的问题是,它无法将form = new Forms.BoxWhiskerPlotForm(); type T转换为public class BoxWhiskerPlotForm : Form BaseType Form

private void ShowForm<T>(Form form)
{
    // Check if the Form already exists. Create it if not.
    if (form == null || form.IsDisposed)
        form = Activator.CreateInstance<T>();

    // Check if the Form is already visible.
    if (form.Visible == false)
        // Show the Form if it isn't.
        form.Show(
            new WindowImplementation(new IntPtr(Globals.ThisAddIn.Application.Windows[1].Hwnd)));
    else
        // Refresh if it is.
        form.Refresh();

    // Bring the Form to the front.
    form.BringToFront();
}

1 个答案:

答案 0 :(得分:4)

您只需要使用类类型约束约束T。您还可以 添加new()约束以使代码更简单:

private void ShowForm<T>(T form) where T : Form, new()
{
    // Check if the Form already exists. Create it if not.
    if (form == null || form.IsDisposed)
    {
        form = new T();
    }
}
相关问题