繁体   English   中英

为什么此通用方法要求T具有公共的无参数构造函数?

[英]Why does this generic method require T to have a public, parameterless constructor?

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

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

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

您还在寻找什么?

要修改的问题:

 iList = Populate.GetList<dataItem>() 

“数据项”是一个变量。 您要在此处指定类型:

 iList = Populate.GetList<T>() 

类型“ T”必须具有公共的无参数构造函数,才能在通用类型GetList:new()中将其用作参数“ T”

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

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

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

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

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

如果是这样,您可能想要这样:

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

然后您这样称呼:

IList<int> result = GetRecords<int>();

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

实际上,我怀疑ref在这里是个好策略。 一推,可能会执行out (因为您不读取该值),但是返回值更简单(且更期望)是:

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

当然,在那时,调用者还可以直接调用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与<T>一起使用,它将在运行时根据需要接受类型。

Getrecords<T> ...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM