首页 > 解决方案 > 聚合的自定义名称

问题描述

在使用不同的聚合器工厂时,是否有一种方法或覆盖允许为返回标签定义自定义名称。例如,调用 SumAggregatoryFactory 对“Amount”字段求和将返回“Sum of Amount”的行标签。如果我们希望它是“总金额”、“总计”或其他自定义值怎么办?

标签: c#nreco

解决方案


创建一个ResultAmount类。这将返回结果的描述,而不是字符串。像这样的东西:

        class ResultAmount
        {
            public string Label { get; set; }
            public decimal SumAmount { get; set; }

            public override string ToString()
            {
                return $"{Label}: {SumAmount}";
            }
        }

对于不同的工厂,Label值可能不同。然后你有一个工厂:

        class TotalCalculations
        {
            public ResultAmount SumAggregatoryFactory()
            {
                return new ResultAmount
                {
                    Label = "Total",
                    SumAmount = 100
                };
            }
        }

以及调用工厂的要点:

    class BillingService
    {
        public void Print(TotalCalculations calc)
        {
            //when calling the method, you can use the standard Label                
            string original = calc.SumAggregatoryFactory().ToString();

             //or take only the sum and configure the result string yourself
            string custom = $"My message: {calc.SumAggregatoryFactory().SumAmount}";
        }
    }

推荐阅读