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

C# foreach遍历XML节点存入List时所有元素均为最后一条如何解决

问题原因分析

你遇到的问题是引用类型实例复用导致的:

  • TestResultsModel是类(引用类型),你把TestResultsModel testRecord = new TestResultsModel();这行代码写在了foreach循环的外部,整个循环过程中只会创建1个testRecord对象实例
  • 每次循环你修改的都是这同一个实例的属性值,调用Add方法往列表里添加的也只是这个实例的内存引用,不是新的对象
  • 最终列表里的所有条目都指向同一个内存地址,自然展示的都是最后一次赋值的属性值
修复方案

把testRecord的实例化逻辑移到foreach循环内部,每次循环都创建一个全新的TestResultsModel对象即可,修改后的代码如下:

//Test Node Details - If not passed
if (record.PCBResult != "Passed")
{
    record.TestResults = new List<TestResultsModel>();
    foreach (XElement element in xmlDoc.Descendants("Test"))
    {
        // 每次循环创建新的实例
        TestResultsModel testRecord = new TestResultsModel();
        testRecord.TestName = element.Attribute("Name").Value;
        testRecord.TestType = element.Attribute("Type").Value;
        testRecord.TestItemNumber = element.Attribute("Itemnumber").Value;
        testRecord.TestSide = element.Attribute("Side").Value;
        testRecord.TestResult = element.Attribute("Result").Value;
        testRecord.TestFailure = element.Attribute("Failure").Value;
        testRecord.TestAoiFailure = element.Attribute("AOIFailure").Value;
        
        record.TestResults.Add(testRecord);
    }
}
补充说明

如果你的TestResultsModel是结构体(值类型)不会出现这个问题,但实际开发中这类数据承载模型基本都定义为类,所以只要涉及循环生成多个实例的场景,一定要在循环内部完成实例化操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:15:02