문제

I have an Ascii class to help me manage and string with char limits, and i want to be able to increment it like a char, so I have some operator overloads. Given the following code:

 public static AsciiWord operator++(AsciiWord aWord){
        aWord.numValue++;
        return aWord.Copy();
    }

Do I really need the copy?

Note: Copy is a extension method I copied off of SO that performs a deep copy of just about anything.

도움이 되었습니까?

해결책

The increment operator is supposed to leave the original value unchanged, and return an incremented copy of it. However, in your implementation, you're mutating the aWord passed in as an argument.

E.g., the following code uses the post-fix increment operator and expects oldValue.NumValue to be 0, but with your current implementation it will be 1.

AsciiWord aWord = new AsciiWord { NumValue = 0 };
AsciiWord oldValue = aWord++;
Assert.Equal(0, oldValue.NumValue); // fails

int i = 0;
int oldIntValue = i++;
Assert.Equal(0, oldIntValue); //passes

In other words - AsciiWord should be deeply immutable.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top