.net C语言中的算子重载与Linq和#

.net C语言中的算子重载与Linq和#,.net,linq,c#-4.0,operator-overloading,.net,Linq,C# 4.0,Operator Overloading,我有一个自定义类型(Money),它隐式转换为decimal,并为+使用重载运算符。当我有这些类型的列表并调用linqSum方法时,结果是十进制的,而不是Money。我怎样才能让+操作员主持并从金额中返还资金 internal class Test { void Example() { var list = new[] { new Money(10, "GBP"), new Money(20, "GBP") }; //this line fails

我有一个自定义类型(
Money
),它隐式转换为decimal,并为
+
使用重载运算符。当我有这些类型的列表并调用linq
Sum
方法时,结果是十进制的,而不是
Money
。我怎样才能让
+
操作员主持并从
金额中返还资金

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;
    }
}

Sum
只知道
系统中的数字类型

您可以像这样使用
Aggregate

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

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

我最后添加了我自己的
Sum
public static class MoneyHelpers{public static Money Sum(这个IEnumerable源,函数选择器){var Money=source.Select(选择器);返回货币。聚合((x,y)=>x+y);}