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

如何在C#中创建带基于列表计算字段的嵌套对象

解决方案

先给出可正常运行并实现自动计算的代码版本,再拆解问题原因:

using System;
using System.Collections.Generic;
using System.Linq; // 必须引入该命名空间才能使用Linq的Sum方法

public class Order // 补充你遗漏的外部类定义
{
    public string Test { get; set; }

    // 初始化列表避免空引用,同时设为public供外部赋值
    public List<Line> Detail { get; set; } = new List<Line>();

    public decimal Total 
    { 
        get => CalculateTotal();
    }

    private decimal CalculateTotal() 
    {
        // 空条件运算符+空合并运算符,避免Detail为null时抛出异常
        return Detail?.Sum(line => line.Cost) ?? 0;
    }

    public class Line 
    {
        // 按C#规范属性名首字母大写,同时设为public让外部可访问
        public int IndexOf { get; set; }
        public decimal Cost { get; set; }
    }
}

你遇到的核心问题拆解:

  1. Linq Sum无提示:没引入System.Linq命名空间,Linq扩展方法(包括Sum)都定义在此空间下,不引入IDE不会提示这些方法。
  2. Cost字段无法访问:原Line类中Cost是默认的private访问修饰符,外部方法CalculateTotal无法读取私有成员,必须改为public(如果Line是内部嵌套类,也可用internal,但public通用性更强)。
  3. 空引用风险:如果Detail未初始化就调用Sum会抛出异常,所以要么在声明时初始化Detail = new List<Line>(),要么用?.空条件运算符配合??空合并运算符返回默认值0。
  4. 可选简化写法:可以直接把Total的getter简化,省去单独的计算方法:
public decimal Total => Detail?.Sum(line => line.Cost) ?? 0;

内容的提问来源于stack exchange,提问作者Brent White - Badger

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:45:28