【发布时间】:2019-11-20 02:22:52
【问题描述】:
我有两个表单:Form_Main 和 Form_Child,我必须在 Form_Main 中实例化 Form_Child。 Form main 有一个 List,Form_Child 的构造函数有一个通用 List。 当我尝试实例化子窗体时,我收到以下错误消息: 错误 1 非泛型类型 'GenericParameterToFormConstructor.Form_Child' 不能与类型参数一起使用。 form_Main的代码是:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GenericParameterToFormConstructor
{
public partial class Form_Main : Form
{
public Form_Main()
{
InitializeComponent();
_list = new List<int>() { 1, 2, 3, 4, 5 };
Form_Child child = new Form_Child<int>(_list);
}
private List<int> _list;
}
}
Form_Child 的代码是:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GenericParameterToFormConstructor
{
public partial class Form_Child<T> : Form
{
public Form_Child(List<T> list)
{
InitializeComponent();
}
}
}
我做错了什么?请帮忙。 提前谢谢你。
【问题讨论】:
-
您还需要在变量名之前指定类型参数。
-
不要玷污表单的类型/构造函数。您可以在
Form_Child中使用可以接受<T>的公共方法(例如public void MyPublicMethod<T>(IList<T> myList))。如果您的列表只是int类型,则不需要泛型类型。 -
@Ron Beyer 谢谢你,但我不清楚你的评论。您介意发布一个简短的代码示例吗?
-
在创建
Form_Child的新实例后调用该方法:var child = new Form_Child(); child.MyPublicMethod(new List<int>(new[] { 1, 2, 3, 4, 5 })); child.Show(); -
改成
var child = new Form_Child<int>(_list);