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

What's the correct way to implement operator ++ for value-types?

我正在研究数字结构的自定义实现,使用非常不同的方式来存储和操作数值。

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

我正在尝试实现 ++-- 运算符,但我 运行 有点困惑:
你是如何完成作业的?
还是平台会自动处理,我只需要 return 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;
    }
}

EDIT:我认为这不是关于递增和递减运算符的其他问题的重复,因为这涉及的值类型的行为不同于 类语境。我知道关于 ++-- 也适用类似的规则,但我相信这个问题的上下文足够不同,并且足够细微,可以独立存在。

数字 class 将具有某种类型的值,如 属性。

public static Number operator ++(Number n)
{
    // ref seems to be required,
    // otherwise this assignment doesn't affect the original variable?
    n.value = n.value + 1;
    return n;
}

这应该可以满足您的要求。

我用你的结构写了这个并添加了值 属性。

private static void Main(string[] args)
{
    var x = new Number();
    x.value = 3;
    x++;
    Console.WriteLine(x.value);
    Console.Read();
}

这正确地生成了一个 4

语句 num++; 本身扩展为 num = PlusPlusOperator(num);。由于您的数据类型是不可变的,因此只需 return n+1;,编译器将处理其余的。

The struct is fully immutable - all fields are implemented as readonly

好!

I'm trying to implement the ++ and -- operators, and I've run into a little confusion: How do you perform the assignment?

你不知道。记住 ++ 运算符的作用。无论是前缀还是后缀:

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

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

Or does the platform handle this automatically, and I just need to return n + 1?

是的,这样做。

++-- 运算符的处理在 C# 语言规范的第 7.7.5 节前缀递增和递减运算符中进行了描述:

The run-time processing of a prefix increment or decrement operation of the form ++x or --x consists of the following steps:

• If x is classified as a variable:

  o x is evaluated to produce the variable.

  o The selected operator is invoked with the value of x as its argument.

  o The value returned by the operator is stored in the location given by the evaluation of x.

  o The value returned by the operator becomes the result of the operation.

因此这些运算符的自定义重载只需要产生一个 incremented/decremented 值。其余的由编译器处理。