为什么这个泛型方法要求T有一个公共的无参数构造函数?

1 c# generics

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

dataItem可以是我的订单对象或用户对象,它将在运行时决定.上面不起作用,因为它给我这个错误类型'T'必须有一个公共无参数构造函数,以便将它用作参数'T'in通用类型

Jam*_*ran 6

public void GetRecords<T>(ref IList<T> iList, T dataitem)
{
}
Run Code Online (Sandbox Code Playgroud)

你还在寻找什么?

修改问题:

 iList = Populate.GetList<dataItem>() 
Run Code Online (Sandbox Code Playgroud)

"dataitem"是一个变量.您想在那里指定类型:

 iList = Populate.GetList<T>() 
Run Code Online (Sandbox Code Playgroud)

类型'T'必须具有公共无参数构造函数,以便在泛型类型GetList中将其用作参数'T':new()

这就是说当你定义Populate.GetList()时,你就像这样声明:

IList<T> GetList<T>() where T: new() 
{...}
Run Code Online (Sandbox Code Playgroud)

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

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