使用泛型方法调用泛型方法

bAN*_*bAN 6 c# generics

我很生气,因为我想从另一个通用方法调用泛型方法..

这是我的代码:

public List<Y> GetList<Y>(
                string aTableName,
                bool aWithNoChoice)
{
  this.TableName = aTableName;
  this.WithNoChoice = aWithNoChoice;

  DataTable dt = ReturnResults.ReturnDataTable("spp_GetSpecificParametersList", this);

  //extension de la classe datatable
  List<Y> resultList = (List<Y>)dt.ToList<Y>();

  return resultList;  
}
Run Code Online (Sandbox Code Playgroud)

所以实际上当我调用ToList时,他是DataTable类的扩展(在这里学习)

编译器说Y不是非抽象类型,他不能将它用于.ToList <>泛型方法..

我究竟做错了什么?

谢谢阅读..

Ani*_*Ani 11

将方法签名更改为:

public List<Y> GetList<Y>(
                string aTableName,
                bool aWithNoChoice) where Y: new()
Run Code Online (Sandbox Code Playgroud)

您需要的原因是因为您使用的自定义扩展方法new()对其泛型类型参数强加了约束.它当然需要,因为它创建了这种类型的实例来填充返回的列表.

显然,您还必须使用泛型类型参数调用此方法,该参数表示具有公共无参数构造函数的非抽象类型.


Mar*_*ell 5

听起来你需要:

public List<Y> GetList<Y>(
     string aTableName,
     bool aWithNoChoice) where Y : class, new()
{ ... }
Run Code Online (Sandbox Code Playgroud)

  • WHERE Y:new()和Y:class,new()之间有什么区别?谢谢你的回复! (2认同)
  • @bAN - `其中Y:class`确保`Y`是*引用类型*(最有可能是`class`).实际上你可能不需要这个 - 重新阅读链接的`ToList`它只需要`其中Y:new()`,所以@Ani的答案是正确的. (2认同)