首页 > 解决方案 > 可以返回任何类型列表的函数

问题描述

我正在编写一个函数,其中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();
                }
            }
        }

标签: c#list

解决方案


您的方法的问题是您的类型没有太多共同点。仅仅因为某些类具有某种继承关系并不意味着该类的列表具有相同的关系。换句话说: a不能转换List<Derived>为。List<Base>

如果 aList<T>是协变的,您可以实现这一点 - 这不是出于以下原因。想象一下,您的ConvertToList-method 的客户端执行以下操作:

var list = ConvertToList<MyBaseClass>(theTable, 1)

现在您还可以执行以下操作:

list.Add(new ProductionRecent());

这可能不是你想要的。因此,您需要一些只读集合,这意味着您不能向其中添加实例。因此IEnumerable<T>-interface协变的,可以用作您的方法的返回类型。


推荐阅读