简体   繁体   中英

Why should I use implicit/explicit operator?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM