.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
相关产品推荐
相关产品推荐

