亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將 List<T> 轉換為 List<myType>

將 List<T> 轉換為 List<myType>

C#
慕尼黑5688855 2021-09-19 18:55:21
當調用任何轉換函數錯誤出現時: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 回答

?
阿晨1998

TA貢獻2037條經驗 獲得超6個贊

嘗試在傳遞給您的方法之前進行轉換:


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;

}


查看完整回答
反對 回復 2021-09-19
  • 1 回答
  • 0 關注
  • 400 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號