C # postfix and prefix increment / decrement overload difference

Most sources say that overloading ++ and - operators in C # leads to overloading both the postfix and the prefix immediately. But it looks like their behavior is still different.

class Counter
{
    public Counter(int v = 0)
    {
        this.v = v;
    }
    public Counter(Counter c)
    {
        v = c.v;
    }
    public int GetValue() { return v; }
    public static Counter operator ++(Counter c)
    {
        c.v++;
        return new Counter(c);
    }
    private int v;
}


class Program
{
    public static void Main()
    {
        Counter c1 = new Counter(1);

        Counter c2 = c1++;

        Counter c3 = ++c1;

        c3++;

        System.Console.WriteLine("c1 = {0}", c1.GetValue());
        System.Console.WriteLine("c2 = {0}", c2.GetValue());
        System.Console.WriteLine("c3 = {0}", c3.GetValue());
    }
}

Miraculously, although the overloaded one operator ++returns a copy of the source class, in this example c1they c3become references to the same object, but c2point to another ( c1=4, c2=2, c3=4here). Change Counter c3 = ++c1;to Counter c3 = c1++;displays c1=3, c2=2, c3=4.

So, what is the exact difference between increment and decrement prefix and prefix, and how does it affect overload? Are these operators the same for classes and primitive types?

+2
source share
1 answer

#. , ; , , .: -)

, :

http://ericlippert.com/2013/09/25/bug-guys-meets-math-from-scratch/

dtb, :

    public static Counter operator ++(Counter c)
    {
        return new Counter(c.v + 1);
    }

# . , , . .

:

    Counter c1 = new Counter(1);

, c1 W. W.v 1.

    Counter c2 = c1++;

:

temp = c1
c1 = operator++(c1) // create object X, set X.v to 2
c2 = temp

, c1 X, c2 W. W.v 1 X.v 2.

    Counter c3 = ++c1;

temp = operator++(c1) // Create object Y, set Y.v to 3
c1 = temp
c3 = temp

, c1 c3 Y, Y.v - 3.

    c3++;

c3 = operator++(c3) // Create object Z, set Z.v to 4

, :

c1.v = 3 (Y)
c2.v = 1 (W)
c3.v = 4 (Z)

X .

, c1, c2 c3 .

+9

All Articles