Post-increment Operator Overloading

前端 未结 3 1680
孤独总比滥情好
孤独总比滥情好 2020-12-03 08:08

I\'m having problems trying to overload the post increment operator in C#. Using integers we get the following results.

int n;

n = 10;
Console.WriteLine(n);         


        
3条回答
  •  醉梦人生
    2020-12-03 08:49

    My first thought was to point out that the normal semantics of ++ are in-place modification. If you want to mimic that you'd write:

    public static Account operator ++(Account a)
    {
        a.Balance += 1;
        return a;
    }
    

    and not create a new object.

    But then I realized that you were trying to mimic the post increment.

    So my second thought is "don't do that" -- the semantics don't map well at all onto objects, since the value being "used" is really a mutable storage location. But nobody likes to be told "don't do that" by a random stranger so I'll let Microsoft tell you not to do it. And I fear their word is final on such matters.

    P.S. As to why it's doing what it does, you're really overriding the preincrement operator, and then using it as if it were the postincrement operator.

提交回复
热议问题