我很生气,因为我想从另一个泛型方法调用一个泛型方法..
这是我的代码:
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;
}
所以实际上当我调用 ToList 时,它是 DataTable 类的扩展(学习了 Here )
编译器说 Y 不是非抽象类型,他不能将它用于 .ToList<> 泛型方法..
我做错了什么?
感谢阅读..
最佳答案
将方法签名更改为:
public List<Y> GetList<Y>(
string aTableName,
bool aWithNoChoice) where Y: new()
您需要它的原因是因为您使用的自定义扩展方法对其泛型类型参数施加了 new()
约束。它当然需要,因为它创建了这种类型的实例来填充返回的列表。
显然,您还必须使用代表具有公共(public)无参数构造函数的非抽象类型的泛型类型参数调用此方法。
关于c# - 用泛型方法调用泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4323367/