我很生气,因为我想从另一个通用方法调用泛型方法..
这是我的代码:
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()对其泛型类型参数强加了约束.它当然需要,因为它创建了这种类型的实例来填充返回的列表.
显然,您还必须使用泛型类型参数调用此方法,该参数表示具有公共无参数构造函数的非抽象类型.
听起来你需要:
public List<Y> GetList<Y>(
string aTableName,
bool aWithNoChoice) where Y : class, new()
{ ... }
Run Code Online (Sandbox Code Playgroud)