ili*_*ian 11 .net linq operator-overloading c#-4.0
我有一个自定义类型(Money)有一个implict转换为十进制和一个重载运算符+.当我有这些类型的列表并调用linq Sum方法时,结果是十进制,而不是Money.我如何给+运营商总统并从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;
}
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*ler 14
Sum只知道数字类型System.
你可以Aggregate像这样使用:
Money result = list.Aggregate((x,y) => x + y);
Run Code Online (Sandbox Code Playgroud)
因为这是调用Aggregate<Money>,它将使用你的Money.operator+并返回一个Money对象.
| 归档时间: |
|
| 查看次数: |
1931 次 |
| 最近记录: |