微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.net – 运算符重载和Linq总和在C#

我有一个自定义类型(M​​oney),它具有对十进制的隐含转换和一个重载的运算符.当我有这些类型的列表并调用 linq Sum方法结果是十进制,而不是金钱.如何给予经营者前提,并从金额返还资金?
internal class Test
{
    void Example()
    {
        var list = new[] { new Money(10,"GBP"),new Money(20,"GBP") };
        //this line fails to compile as there is not implicit 
        //conversion from decimal to money
        Money result = list.Sum(x => x);
    }
}


public class Money
{
    private Currency _currency;
    private string _iso3LetterCode;

    public decimal? Amount { get; set; }
    public Currency Currency
    {
        get {  return _currency; }
        set
        {
            _iso3LetterCode = value.Iso3LetterCode; 
            _currency = value; 
        }
    }

    public Money(decimal? amount,string iso3LetterCurrencyCode)
    {
        Amount = amount;
        Currency = Currency.FromIso3LetterCode(iso3LetterCurrencyCode);
    }

    public static Money operator +(Money c1,Money c2)
    {
        if (c1.Currency != c2.Currency)
            throw new ArgumentException(string.Format("Cannot add mixed currencies {0} differs from {1}",c1.Currency,c2.Currency));
        var value = c1.Amount + c2.Amount;
        return new Money(value,c1.Currency);
    }

    public static implicit operator decimal?(Money money)
    {
        return money.Amount;
    }

    public static implicit operator decimal(Money money)
    {
        return money.Amount ?? 0;
    }
}

解决方法

总和只知道系统中的数字类型.

你可以这样使用Aggregate:

Money result = list.Aggregate((x,y) => x + y);

因为这是调用Aggregate< Money>,它将使用您的Money.operator并返回一个Money对象.

原文地址:https://www.jb51.cc/csharp/96011.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐