문제

Check the code bellow:

class Money
{
    public Money(decimal amount)
    {
        Amount = amount;
    }

    public decimal Amount { get; set; }

    public static implicit operator decimal(Money money)
    {
        return money.Amount;
    }

    public static explicit operator int(Money money)
    {
        return (int)money.Amount;
    }
}

I don't understand how it would be useful in my code, couldn't I just do a method like:

public static int returnIntValueFrom(Money money)
{
    return (int)money.Amount;
}

Wouldn't it be easier and clearer to implement?

도움이 되었습니까?

해결책

This is done to allow for money to be added to other money. Without that piece of code, this would cause a compiler error, "Operator '+' cannot be applied to operands of type 'Money' and 'int'"

Money money = new Money(5.35m);
decimal net = money + 6;

With the casting operator present it allows these types of conversions to be made without throwing an exception. It can assist in readability and allow for polymorphism where different currencies could implement their own types of casts for example.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top