本文介绍了运算符重载和LINQ总和在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个自定义类型(理财
),有一个隐式的转换为十进制和重载运算符 +
。当我有这种类型的列表,并调用LINQ 总和
方法的结果是小数,而不是理财
。我怎么可以给 +
操作符presidence和回款的总和
?
内部类测试
{
void示例()
{
VAR名单=新的[] {新钱(10,英镑),新钱(20,英镑)};
//此行编译失败,因为没有隐
//转换从十进制的钱
金钱的结果= list.Sum(X => X);
}
}
公共类理财
{
私人货币_currency;
私人字符串_iso3Letter code;
公共小数?金额{获得;组; }
公共外币货币
{
{返回_currency; }
组
{
_iso3Letter code = value.Iso3Letter code;
_currency =价值;
}
}
公款(十进制?量,串iso3LetterCurrency code)
{
金额=金额;
货币= Currency.FromIso3Letter code(iso3LetterCurrency code);
}
公共静态钱运营商+(钱C1,C2的钱)
{
如果(c1.Currency!= c2.Currency)
抛出新的ArgumentException(的String.Format(无法添加混合货币{0}不同于{1},
c1.Currency,c2.Currency));
VAR值= c1.Amount + c2.Amount;
返回新的货币(值,c1.Currency);
}
公共静态隐含的运营商小数?(钱生钱)
{
返回money.Amount;
}
公共静态隐含运营十进制(钱生钱)
{
返回money.Amount? 0;
}
}
解决方案
总和
只知道数类型系统
。
您可以使用总结
是这样的:
理财结果= list.Aggregate((X,Y)=> X + Y);
由于这是调用总结<钱>
,它会使用你的 Money.operator +
并返回理财
对象。
I have a custom type (Money
) that has an implict conversion to decimal and an overloaded operator for +
. When I have a list of these types and call the linq Sum
method the result is decimal, not Money
. How can I give the +
operator presidence and return Money from the 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;
}
}
解决方案
Sum
only knows about the number types in System
.
You can use Aggregate
like this:
Money result = list.Aggregate((x,y) => x + y);
Because this is calling Aggregate<Money>
, it will use your Money.operator+
and return a Money
object.
这篇关于运算符重载和LINQ总和在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!