为嵌套输出重用相同的 POCO 类

问题描述

我有一个 .NET Core API,它必须返回以下输出

{
   "TotalValue":200,"Count":100,"TypeA":
   {
    "TotalValue":200,"Count":100   
   }
   "TypeB":
   {
    "TotalValue":200,"Count":100   
   }
}

我尝试了以下方法来实现这一点,

 public interface IValue
    {
        public int TotalValue { get; set; }
        public int Count { get; set; }
    }

    public class Type : IValue
    {
        public int TotalValue { get; set; }
        public int Count { get; set; }
    }

    public class Test
    {
        public int TotalValue 
        {
            get 
            {
                return TypeA?.TotalValue ?? 0 + TypeB?.TotalValue ?? 0;
            }
        }
        public int Count 
        {
            get
            {
                return TypeA?.Count ?? 0 + TypeB?.Count ?? 0;
            }
        } 

        public Type TypeA { get; set; }
        public Type TypeB { get; set; }
    }

但是这些值根本没有添加,我觉得即使我让它工作,也可以通过这种方式避免很多重复,有没有更优雅的解决方案来实现这一点?

我必须分别设置 TypeA 和 TypeB 的值,TypeA 的值被设置,但是当我将值设置为 TypeB 时,求和没有发生。

解决方法

由于运算符 ?? 的优先级,求和似乎没有发生。当你写这个:

TypeA?.TotalValue ?? 0 + TypeB?.TotalValue ?? 0;

实际上可能是这个意思:

(TypeA?.TotalValue) ?? (0 + TypeB?.TotalValue ?? 0);

因此,如果您的 TypeA 不为 null,则仅返回其 TotalValue。来自 TypeB 的值无论是否为空都会被忽略。如果您有 TypeA null 和 TypeB not null。返回的值来自 TypeB.TotalValue

如果您不确定运算符的优先级,您应该明确地使用括号以您想要的方式对表达式进行分组。它还有助于使表达更清晰。

要修复它,只需像这样按您想要的方式(据我所知)分组:

public int TotalValue 
{
     get 
     {
         return (TypeA?.TotalValue ?? 0) + (TypeB?.TotalValue ?? 0);
     }
}
public int Count 
{
     get
     {
         return (TypeA?.Count ?? 0) + (TypeB?.Count ?? 0);
     }
}