开发者

overloading ++ C#

开发者 https://www.devze.com 2023-03-02 23:09 出处:网络
public static MyClass operator++(MyClass op) { MyClass result = new MyClass(); // MyClass() x=y=z=0; result.x = op.x + 1;
public static MyClass operator++(MyClass op)
{
    MyClass result = new MyClass(); // MyClass() x=y=z=0; 

    result.x = op.x + 1;
    result.y = op.y + 1;
    result.z = op.z + 1;

    return result:
}

//...

public void Main()
{
    MyClass c = new MyClass();
    MyClass b = new MyClass(1,2,开发者_C百科3); //ctor x = 1, ...
    c = b++;
}

The question is why variable b going to change? because result.x = op.x + 1; shouldn't change op.x result actually is c is (1,2,3) b is (2,3,4) I don't understand why not c is (2,3,4) and b is (1,2,3)


You say, "because result.x = op.x + 1 shouldn't change op.x." But ++ is not the same as + 1. It is the standard postfix increment operator which increments the operand b by using your custom overload -- it assigns the new value to b immediately after passing the previous value to c. If it were the prefix operator (++b), it would have incremented before passing the value to c.

Without any overloads at all, the code:

b++

Is equivalent to:

b = b + 1

And

c = b++ 

Is equivalent to:

c = b;
b = b + 1;

Now using your overload, it's more equivalent to:

c = b;
b = call_your_++_overload(b);


Behaviour you are describing is according to the documentation:

postfix increment operation - The result of the operation is the value of the operand before it has been incremented.

Both b++ (postfix operator) and ++b (prefix operator) changes original variable. To get desired results I would suggest overloading + operator and change c = b++; to c = b + 1;

0

精彩评论

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

关注公众号