【问题标题】:C# Pass generic List to WinForm constructor [duplicate]C#将通用列表传递给WinForm构造函数[重复]
【发布时间】: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 中使用可以接受&lt;T&gt; 的公共方法(例如public void MyPublicMethod&lt;T&gt;(IList&lt;T&gt; myList))。如果您的列表只是int 类型,则不需要泛型类型。
  • @Ron Beyer 谢谢你,但我不清楚你的评论。您介意发布一个简短的代码示例吗?
  • 在创建Form_Child 的新实例后调用该方法:var child = new Form_Child(); child.MyPublicMethod(new List&lt;int&gt;(new[] { 1, 2, 3, 4, 5 })); child.Show();
  • 改成var child = new Form_Child&lt;int&gt;(_list);

标签: c# winforms generics


【解决方案1】:

可能还有一个 Form_Child.designer.cs 文件,其中包含该部分类的另一部分。我很确定其中没有泛型参数&lt;T&gt;,因为它不符合具有泛型参数的表单派生类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-22
    • 1970-01-01
    • 2011-12-22
    • 2017-03-17
    • 1970-01-01
    • 2020-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多