开发者

Overloading the "Set to equal to" operator

I was reading a Business Primitives by CodeBetter.com and was toying around with the idea.

Taking his example of Money, how would one implement this in a way that it can be used similarily as regular value types?

What I mean by that is do this:

Money myMoney = 100.00m;

Instead of:

Money myMoney = new Money(100.00m);

I understand h开发者_开发百科ow to override all the operators to allow for functionality doing math etc, but I don't know what needs to be overriden to allow what I'm trying to do.

The idea of this is to minimize code changes required when implementing the new type, and to keep the same idea that it is a primitive type, just with a different value type name and business logic functionality.

Ideally I would have inherited Integer/Float/Decimal or whatever required, and override as needed, however obviously that is not available to structures.


You could provide an implicit cast operator from decimal to Money like so:

class Money {
    public decimal Amount { get; set; }
    public Money(decimal amount) {
        Amount = amount;
    }
    public static implicit operator Money(decimal amount) {
        return new Money(amount);
    }
}

Usage:

Money money = 100m;
Console.WriteLine(money.Amount);

Now, what is happening here is not that we are overloading the assignment operator; that is not possible in C#. Instead, what we are doing is providing an operator that can implicitly cast a decimal to Money when necessary. Here we are trying to assign the decimal literal 100m to an instance of type Money. Then, behind the scenes, the compiler will invoke the implicit cast operator that we defined and use that to assign the result of the cast to the instance money of Money. If you want to understand the mechanisms of this, read §7.16.1 and §6.1 of the C# 3.0 specification.

Please note that types that model money should be decimal under-the-hood as I have shown above.


Please go through to get more clarity about this http://www.csharphelp.com/2006/03/c-operator-overloading/


The assignment operator cannot be defined in C#, but for this kind of assignment you can overload the implicit cast operator:

(inside Money class)

public static implicit operator Money(double value)
{
    return new Money(value);
}

Note: I recommend using decimal for accurate money calculation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜