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

如何在递归函数中返回列表并保留列表数据?

问题分析与修复方案

你的问题并非列表被重置,而是对象引用复用导致的错误:你在循环外部仅创建了一个InsuranceMenuItem实例,每次循环只是修改这个实例的name和id属性,再将同一个实例添加到列表中。由于列表存储的是对象引用,最终所有列表项指向的都是同一个对象,因此看起来只有最后一次循环的数据。

修复步骤

将InsuranceMenuItem的实例创建代码移到foreach循环内部,确保每次循环都生成新的对象实例,这样添加到列表的就是独立的对象,各自保留当前循环的属性值。

修正后的完整代码

初始化代码(无需修改)

List<InsuranceMenuItem> insuranceMenuItemsList = new List<InsuranceMenuItem>();
List<InsuranceMenuItem> checktest = new List<InsuranceMenuItem>();
insuranceMenuItemsList = ParseDynamicTreeview((InsurancePartDynamicObject)oInsuranceDynPart, checktest);

修正后的递归方法

private List<InsuranceMenuItem> ParseDynamicTreeview(InsurancePartDynamicObject oInsuranceDynPart, List<InsuranceMenuItem> checktest)
{
    InsurancePartBase[] oInsuranceParts = oInsuranceDynPart.GetAllInsuranceParts();
    
    foreach (InsurancePartDynamicObject oInsuranceDynP in oInsuranceParts)
    {
        // 每次循环创建新实例,避免引用复用
        InsuranceMenuItem insuranceMenuItem = new InsuranceMenuItem();
        insuranceMenuItem.name = oInsuranceDynP.Caption;
        insuranceMenuItem.id = Utilities.GetDBInt(oInsuranceDynP.ProductDefinitionObject.DataRow, "ProddefTypeID");
          
        checktest.Add(insuranceMenuItem);
        ParseDynamicTreeview(oInsuranceDynP, checktest);
    }
    return checktest;
}

补充说明

递归调用中你传递的是同一个checktest列表的引用,所以列表本身不会被重置,之前的错误完全是重复使用同一个对象实例导致的。修改后,每个循环迭代都会生成独立的InsuranceMenuItem对象,列表就能正确保存所有层级的数据了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 11:35:27