You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET向嵌套列表对象添加元素报错CS1503,求解决方案

解决方法:类型不匹配导致的AddRange错误

错误CS1503的核心是类型不兼容:你试图将List<DebtSingleOut>直接添加到List<DebtAllDetail>中,但这两个是完全独立的类,C#不允许隐式转换。以下是两种可行的解决方式:

方案1:逐个转换并添加

先确保嵌套列表已初始化(避免空引用异常),然后遍历lstDebtSingleOut,将每个DebtSingleOut实例映射为DebtAllDetail实例后添加:

// 初始化嵌套列表,防止NullReferenceException
if (debtallout.debtalldetail == null)
{
    debtallout.debtalldetail = new List<DebtAllDetail>();
}

// 遍历转换并添加
foreach (var singleItem in lstDebtSingleOut)
{
    debtallout.debtalldetail.Add(new DebtAllDetail
    {
        debtid = singleItem.debtid, // 对应DebtSingleOut的debtid属性
        name = singleItem.name       // 对应DebtSingleOut的name属性
    });
}

方案2:用LINQ批量转换后添加

利用LINQ的Select方法批量转换整个列表,再通过AddRange添加:

// 初始化嵌套列表
if (debtallout.debtalldetail == null)
{
    debtallout.debtalldetail = new List<DebtAllDetail>();
}

// 批量转换并添加
var convertedDetails = lstDebtSingleOut.Select(item => new DebtAllDetail
{
    debtid = item.debtid,
    name = item.name
}).ToList();

debtallout.debtalldetail.AddRange(convertedDetails);

注意事项

  • 如果DebtSingleOut的属性名和DebtAllDetail不一致,要调整映射关系(比如DebtSingleOut用DebtId而不是debtid,则写成debtid = item.DebtId)。
  • 必须确保debtallout.debtalldetail不为null,否则调用Add或AddRange会触发NullReferenceException。

内容的提问来源于stack exchange,提问作者Paulie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 15:55:15