我正在處理一個Number結構的自定義實現,其存儲和操作數值的方式非常不同。什麼是爲值類型實現operator ++的正確方法?
的結構是完全不可改變的 - 所有的領域都實現爲readonly
我試圖實現++
和--
運營商,和我碰到的有點慌亂:
你如何進行分配?
或者平臺自動處理,我只需要返回n + 1
?
public struct Number
{
// ...
// ... readonly fields and properties ...
// ... other implementations ...
// ...
// Empty placeholder + operator, since the actual method of addition is not important.
public static Number operator +(Number n, int value)
{
// Perform addition and return sum
// The Number struct is immutable, so this technically returns a new Number value.
}
// ERROR here: "ref and out are not valid in this context"
public static Number operator ++(ref Number n)
{
// ref seems to be required,
// otherwise this assignment doesn't affect the original variable?
n = n + 1;
return n;
}
}
編輯:我覺得這不是關於增量和減量運算等問題,重複的,因爲這涉及價值類型的行爲不同於在這種情況下類。我知道類似的規則適用於++
和--
,但我相信這個問題的背景是不同的,並且足夠細緻,獨立。
可能重複[如何在我的類中實現pre和post-increment/decrement運算符?](http://stackoverflow.com/questions/3282619/how-to-implement-pre-and-post-increment-遞減運算符在我的類) –