में ऑपरेटर अधिभार और लिंक योग मेरे पास एक कस्टम प्रकार (Money
) है जिसमें +
के लिए दशमलव और ओवरलोडेड ऑपरेटर का एक आरोही रूपांतरण है। जब मेरे पास इन प्रकारों की एक सूची है और 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;
}
}
मैं अपने खुद के 'Sum' सार्वजनिक स्थैतिक कक्षा MoneyHelpers { सार्वजनिक स्थिर धन योग (इस IEnumerable स्रोत, समारोह चयनकर्ता) { वर पैसा = source.Select (चयनकर्ता) जोड़ने समाप्त हो गया; वापसी monies.Aggregate ((एक्स, वाई) => एक्स + वाई); } } –
ilivewithian
ग्रेट टिप। धन्यवाद। – Joe