【发布时间】:2018-12-16 19:32:24
【问题描述】:
我有一个函数可以传入任何类型的list<>。然后该函数确定列表的类型。我的问题是我传入一个列表然后我将其转换但之后当我将我的列表分配给传入的列表时我收到一个错误:
Cannot convert type 'System.Collection.Generic.List<ADMPortal_2.Modles.ProductionPending>' to 'System.Collections.List<T>
代码
在数据表中返回结果的数据库调用,然后将其转换为其列表类型。此函数必须能够返回任何类型的列表,例如列表、列表等
string cnnStr = ConfigurationManager.ConnectionStrings["conChdbd1"].ConnectionString;
OracleConnection cnn;
OracleDataReader dr;
public List<T> Execute<T>(string strSql, List<T> list)
{
using (OracleConnection conn = new OracleConnection(cnnStr))
{
using (OracleCommand objCommand = new OracleCommand(strSql, conn))
{
objCommand.CommandType = CommandType.Text;
DataTable dt = new DataTable();
OracleDataAdapter adp = new OracleDataAdapter(objCommand);
conn.Open();
adp.Fill(dt);
if (dt != null)
{
list = ConvertToList(dt, list).ToList();
}
}
}
return list;
}
分配给列表时发生此错误
public List<T> ConvertToList<T>(DataTable dt, List<T> list)
{
if (list.GetType() == typeof(List<ProductionPending>))
{
list = ConvertToProductionPending(dt, (list as List<ProductionPending>));
}
else if (list.GetType() == typeof(List<ProductionRecent>))
{
list = ConvertToProductionRecent(dt, (list as List<ProductionRecent>));
}
else if (list.GetType() == typeof(List<MirrorDeployments>))
{
list = ConvertToMirror(dt, (list as List<MirrorDeployments>));
}
return list;
}
这里是转换函数
private List<ProductionPending> ConvertToProductionPending(DataTable dt, List<ProductionPending> list)
{
// Convert here
return list;
}
private List<ProductionRecent> ConvertToProductionRecent(DataTable dt, List<ProductionRecent> list)
{
// Convert here
return list;
}
private List<MirrorDeployments> ConvertToMirror(DataTable dt, List<MirrorDeployments> list)
{
// Convert here
return list;
}
【问题讨论】:
-
为什么要在
List<T>上使用.ToList()?当方法只在其中写入并返回时,为什么要将list传递给方法? -
似乎您正在手动执行 EF 和其他 ORM 的操作。我建议您考虑使用现有框架而不是重新发明轮子。
标签: c# list type-conversion