c# - 可以返回任何类型列表的函数
问题描述
我正在编写一个函数,其中DataTable
给出了 a 并且该函数应该识别类型并将数据表转换为其类型的列表。但我的问题是,每当我返回列表时,都会出现错误:
无法隐式转换类型
'System.Collections.Generic.List<ADMPortal_2.Modles.ProductionPending>'
到
'System.Collections.Generic.List<T>'
现在如何创建一个可以返回任何类型的函数list<>
?
例如
List<ProductionPending>
List<ProductionRecent>
List<MirrorDeployments>
功能
public List<T> ConvertToList<T>(DataTable dt, int listType)
{
if (listType == 1)
{
List<ProductionPending> list = new List<ProductionPending>();
list = ConvertToProductionPending(dt);
return list;
}
else if (listType == 2)
{
List<ProductionRecent> list = new List<ProductionRecent>();
ConvertToProductionRecent(dt);
return list;
}
else if (listType == 3)
{
List<MirrorDeployments> list = new List<MirrorDeployments>();
list = ConvertToMirror(dt);
return list;
}
return 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<T>(dt, 1).ToList();
}
}
}
解决方案
您的方法的问题是您的类型没有太多共同点。仅仅因为某些类具有某种继承关系并不意味着该类的列表具有相同的关系。换句话说: a不能转换List<Derived>
为。List<Base>
如果 aList<T>
是协变的,您可以实现这一点 - 这不是出于以下原因。想象一下,您的ConvertToList
-method 的客户端执行以下操作:
var list = ConvertToList<MyBaseClass>(theTable, 1)
现在您还可以执行以下操作:
list.Add(new ProductionRecent());
这可能不是你想要的。因此,您需要一些只读集合,这意味着您不能向其中添加实例。因此IEnumerable<T>
-interface是协变的,可以用作您的方法的返回类型。
推荐阅读
- combinations - 计算集合中子集的数量
- intellij-idea - IntelliJ - 切换项目文件树的键盘快捷键是什么?
- sql - 不要删除变量中的空格
- c# - 如何远程性能分析 Windows 服务?
- mocking - ts-jest 提供模拟测试和模块的不同实例
- r - 尝试使用 tinytex R 包安装 TinyTeX 时出错“无法联系 mirror.ctan.org,返回主干服务器!”
- c++ - 我们如何使用 Google bazel 运行单个测试
- docusignapi - 使用 Apex Toolkit 的发件人 OAuth 流程
- r - 创建绘图后,从 R 中的绘图中删除轴标签
- ruby-on-rails - 在 Rspec 中测试嵌套类方法