c# - 为什么这个泛型方法要求 T 有一个公共(public)的、无参数的构造函数?

标签 c# generics

public void Getrecords(ref IList iList,T dataItem) 
{ 
  iList = Populate.GetList<dataItem>() // GetListis defined as GetList<T>
}

dataItem 可以是我的订单对象或用户对象,这将在运行时决定。以上不起作用,因为它给了我这个错误 类型“T”必须具有公共(public)无参数构造函数才能将其用作泛型类型中的参数“T”

最佳答案

public void GetRecords<T>(ref IList<T> iList, T dataitem)
{
}

您还需要什么?

修改后的问题:

 iList = Populate.GetList<dataItem>() 

“数据项”是一个变量。你想在那里指定一个类型:

 iList = Populate.GetList<T>() 

The type 'T' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type GetList:new()

这就是说,当您定义 Populate.GetList() 时,您是这样声明它的:

IList<T> GetList<T>() where T: new() 
{...}

这告诉编译器 GetList 只能使用具有公共(public)无参数构造函数的类型。你在GetRecords中使用T创建了一个GetList方法(这里的T指的是不同的类型),你必须对它做同样的限制:

public void GetRecords<T>(ref IList<T> iList, T dataitem) where T: new() 
{
   iList = Populate.GetList<T>();
}

关于c# - 为什么这个泛型方法要求 T 有一个公共(public)的、无参数的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/251541/

相关文章:

c# - 在 RadGridView C# 中突出显示空值单元格

c# - 如何在我的 XAML 中使用另一个自定义控件基类,使 WPF 在我的 View 中实例化一个自定义控件?

TypeScript - 通用约束可以提供 "allowed"类型吗?

java - 这个java泛型是什么意思?

java - 从泛型类返回一个数组。如何在 main 方法中打印数组中的数据?

c# - 将背景设置为 Canvas

c# - 没有 NuGet 的工作

c# - 使用 jquery 函数检查 asp.net 标签属性

vb.net - VB.NET 中的泛型

c# - <in From, out To> 是什么意思?