繁体   English   中英

转换清单 <T> 列出 <myType>

[英]Convert List<T> to List<myType>

调用任何Convert函数错误时:

Argument 2: cannot convert from 'System.Collections.Generic.List<T>' to 'System.Collections.Generic.List<ProductionRecent>

我试图传递函数内部的任何列表,确定它必须是哪个列表并进行转换。 有什么建议么?

    public List<T> ConvertToList<T>(DataTable dt, List<T> list)
    {
        if (list.GetType() == typeof(List<ProductionPending>))
        {                
            ConvertToProductionPending(dt, list);   // ERROR
        }
        else if (list.GetType() == typeof(List<ProductionRecent>))
        {
            ConvertToProductionRecent(dt, list);   // ERROR
        }
        else if (list.GetType() == typeof(List<MirrorDeployments>))
        {
            ConvertToMirror(dt list);   // ERROR
        }
        return list;
    }

    private List<ProductionPending> ConvertToProductionPending(DataTable dt, List<ProductionPending> list)
    {
          // do some stuff here
          return list;
    }

    private List<ProductionRecent> ConvertToProductionRecent(DataTable dt, List<ProductionRecent> list)
    {
        // do some stuff here
        return list;
    }
    private List<MirrorDeployments> ConvertToMirror(DataTable dt, List<MirrorDeployments> list)
    {
        // do some stuff here
        return list;
    }

尝试在传递给您的方法之前进行投射:

public List<T> ConvertToList<T>(DataTable dt, List<T> list)
{
    if (list.GetType() == typeof(List<ProductionPending>))
    {                
        ConvertToProductionPending(dt, (list as List<ProductionPending>)); 
    }
    else if (list.GetType() == typeof(List<ProductionRecent>))
    {
        ConvertToProductionRecent(dt, (list as List<ProductionRecent>));   
    }
    else if (list.GetType() == typeof(List<MirrorDeployments>))
    {
        ConvertToMirror(dt, (list as List<MirrorDeployments>));
    }
    return list;
}

编辑:

另外,如果您只是不做任何事情就返回列表,则根本不需要convert方法,只需像List<MirrorDeployments> l2 = (list as List<MirrorDeployments>)

如果您使用的是C#7,则还可以使用模式匹配

public List<T> ConvertToList<T>(DataTable dt, List<T> list)
{
    switch(list)
    {
        case List<ProductionPending> pp:
            //pp is list cast as List<ProductionPending>
            break;
        case List<ProductionRecent> pr:
            //pr is list cast as List<ProductionRecent>
            break;
        case List<MirrorDeployments> md:
            //md is list cast as List<MirrorDeployments>
            break;          
    }
    return list;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM