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

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

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

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

你还在寻找什么?

修改问题:

  iList = Populate.GetList() 

“dataitem”是一个变量。 您想在那里指定一个类型:

  iList = Populate.GetList() 

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

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

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

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

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

您修改后的问题将dataItem作为T类型的对象传递,然后尝试将其用作GetList()的类型参数。 也许你只是作为一种指定T的方式传递dataItem?

如果是这样,你可能想要这样的东西:

 public IList GetRecords() { return Populate.GetList(); } 

然后你这样称呼:

 IList result = GetRecords(); 

要求公共的无参数构造函数的问题只能是因为Populate.GetList需要它 – 即具有“T:new()”约束。 要解决此问题,只需在方法中添加相同的约束即可。

实际上,我怀疑ref是一个很好的策略。 在推送时, out可能会(因为您没有读取该值),但更简单(更期望)的选项是返回值:

 public IList GetRecords(T dataItem) where T : new() { // MG: what does dataItem do here??? return Populate.GetList(); } 

当然,在那时,调用者也可以直接调用Populate.GetList

我怀疑你也可以删除dataItem ……但问题并不完全清楚。

如果您不打算将其作为通用(并且dataItem是模板对象),那么您可以通过MakeGenericMethod执行此操作:

 public static IList GetRecords(object dataItem) { Type type = dataItem.GetType(); return (IList) typeof(Populate).GetMethod("GetList") .MakeGenericMethod(type).Invoke(null,null); } 

您可以使用Generic with ,它将在运行时接受您想要的类型。

 Getrecords ... 

这应该有您需要的任何更详细的信息。 http://msdn.microsoft.com/en-us/library/twcad0zb(VS.80).aspx