为值类型实现operator ++的正确方法是什么?

Gif*_*guy 4 c# struct operator-overloading increment operators

我正在研究Number结构的自定义实现,它具有非常不同的存储和操作数值的方法.

结构是完全不可变的 - 所有字段都实现为 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:我认为这不是关于递增和递减运算符的其他问题的重复,因为这涉及与此上下文中的类行为不同的值类型.我理解类似的规则适用于++--,但我相信这个问题的背景是不同的,并且有足够的细微差别,可以独立存在.

Eri*_*ert 9

结构是完全不可变的 - 所有字段都实现为 readonly

好!

我正在尝试实现++--运算符,我遇到了一些困惑:你如何执行任务?

你没有.记住++操作员的作用.无论是前缀还是后缀:

  • 获取操作数的原始值
  • 计算继任者的价值
  • 存储继任者
  • 产生原始值或后继者

C#编译器不知道如何为您的类型执行该过程的唯一部分是"计算后继者",因此这是被覆盖的++运算符应该执行的操作.只是回归继任者; 让编译器处理如何进行赋值.

或者平台是否自动处理,我只需要返回n + 1

是的,那样做.