将List <t>转换为List <mytype>

时间:2018-07-04 13:14:19

标签: c# asp.net

在调用任何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;
    }

1 个答案:

答案 0 :(得分:2)

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

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,则也可以使用pattern matching

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;
}