为什么此通用方法要求T具有公共的无参数构造函数? [英] Why does this generic method require T to have a public, parameterless constructor?

查看:158
本文介绍了为什么此通用方法要求T具有公共的无参数构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

dataItem可以是我的订单对象或用户对象,它们将在运行时确定上面的方法不起作用,因为它给了我这个错误
类型'T'必须具有公共无参数构造函数才能将其用作通用类型的参数'T'

dataItem can be my order object or user object which will be decided at run time.The above does not work as it gives me this error The type 'T' must have a public parameterless constructor in order to use it as parameter 'T' in the generic type

推荐答案

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

您还在寻找什么?

要修订的问题:

 iList = Populate.GetList<dataItem>() 

dataitem是变量。您要在此处指定类型:

"dataitem" is a variable. You want to specify a type there:

 iList = Populate.GetList<T>() 




类型 T必须具有公共的
无参数构造函数才能使
在通用
类型GetList:new()

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

中将其用作参数'T' Populate.GetList(),您应这样声明:

This is saying that when you defined Populate.GetList(), you declared it like this:

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

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

That tells the compiler that GetList can only use types that have a public parameterless constructor. You use T to create a GetList method in GetRecords (T refers to different types here), you have to put the same limitation on it:

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

这篇关于为什么此通用方法要求T具有公共的无参数构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆