猿问

将 List<T> 转换为 List<myType>

当调用任何转换函数错误出现时:


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;

    }


慕尼黑5688855
浏览 355回答 1
1回答

阿晨1998

尝试在传递给您的方法之前进行转换:public List<T> ConvertToList<T>(DataTable dt, List<T> list){&nbsp; &nbsp; if (list.GetType() == typeof(List<ProductionPending>))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; ConvertToProductionPending(dt, (list as List<ProductionPending>));&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; else if (list.GetType() == typeof(List<ProductionRecent>))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; ConvertToProductionRecent(dt, (list as List<ProductionRecent>));&nbsp; &nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; else if (list.GetType() == typeof(List<MirrorDeployments>))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; ConvertToMirror(dt, (list as List<MirrorDeployments>));&nbsp; &nbsp; }&nbsp; &nbsp; return list;}编辑:另外,如果您只是返回列表而不做任何事情,则根本不需要 convert 方法,只需像 List<MirrorDeployments> l2 = (list as List<MirrorDeployments>)如果您使用的是 C# 7,您还可以使用模式匹配:public List<T> ConvertToList<T>(DataTable dt, List<T> list){&nbsp; &nbsp; switch(list)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; case List<ProductionPending> pp:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //pp is list cast as List<ProductionPending>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case List<ProductionRecent> pr:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //pr is list cast as List<ProductionRecent>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; case List<MirrorDeployments> md:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //md is list cast as List<MirrorDeployments>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; }&nbsp; &nbsp; return list;}
随时随地看视频慕课网APP
我要回答