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/