我有一个自定义类型(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; …Run Code Online (Sandbox Code Playgroud) 首先,我按照本教程创建了我的Money对象:https : //www.codeproject.com/articles/837791/money-pattern
Money totalItems = _invoice.InvoiceDetails
.Sum(y => y.Amount); // Amount is of type Money
Run Code Online (Sandbox Code Playgroud)
我在上收到编译异常y.Amount:
无法将类型'Money'隐式转换为'long?' 无法将lambda表达式转换为预期的委托类型,因为该块中的某些返回类型不能隐式转换为委托返回类型
我究竟做错了什么?
这是我的Money课程:
public class Money
{
public decimal Amount { get; private set; }
public CurrencyCode Currency { get; private set; }
#region Constructors
public Money() { }
public Money(Money amount)
{
this.Amount = amount.Amount;
this.Currency = amount.Currency;
}
public Money(decimal amount, CurrencyCode currencyCode)
{
this.Amount = amount;
this.Currency = currencyCode;
}
public Money(int amount, CurrencyCode currency)
: …Run Code Online (Sandbox Code Playgroud)