C# 将方法转换为泛型以便与表单一起重用
我正在为Excel开发一个统计外接程序,下面的方法适用于我必须绘制的每个绘图。我有大约10个不同的绘图,每次只有C# 将方法转换为泛型以便与表单一起重用,c#,generics,C#,Generics,我正在为Excel开发一个统计外接程序,下面的方法适用于我必须绘制的每个绘图。我有大约10个不同的绘图,每次只有表单的类型发生变化 private void ShowBoxWhiskerPlotForm() { // Check if the Form already exists. Create it if not. if (_boxWhiskerPlotForm == null || _boxWhiskerPlotForm.IsDisposed) _boxWh
表单的类型
发生变化
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()的硬调用代码>。这里的问题是,它无法将t
的类型
转换为基类型
表单
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();
}
私人作废展示表格(表格)
{
//检查表单是否已存在。如果不存在,请创建它。
if(form==null | | form.IsDisposed)
form=Activator.CreateInstance();
//检查表单是否已可见。
if(form.Visible==false)
//如果不是,请显示表单。
表演(
新的窗口实现(新的IntPtr(Globals.ThisAddIn.Application.Windows[1].Hwnd));
其他的
//如果是,请刷新。
form.Refresh();
//把表格放在前面。
形式.BringToFront();
}
您只需要使用类类型约束约束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();
}
}
private void ShowForm(T form),其中T:form,new()
{
//检查表单是否已存在。如果不存在,请创建它。
if(form==null | | form.IsDisposed)
{
form=新的T();
}
}
您只需要使用类类型约束约束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();
}
}
private void ShowForm(T form),其中T:form,new()
{
//检查表单是否已存在。如果不存在,请创建它。
if(form==null | | form.IsDisposed)
{
form=新的T();
}
}
对不起,有什么问题吗?类BoxWhiskerPlotForm:Form->无法转换为基类型?所有这些表单都将从“表单”继承,对吗?您不能将其用作基类型吗?怎么了?对不起,怎么了?类BoxWhiskerPlotForm:Form->无法转换为基类型?所有这些表单都将从“表单”继承,对吗?您不能将其用作基类型吗?为什么?这就是我要找的。多谢各位!这就是我要找的。多谢各位!