gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:18:34 25 4
gpt4 key购买 nike

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

该结构是完全不可变的 - 所有字段都实现为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;
}
}

编辑:我认为这不是关于递增和递减运算符的其他问题的重复,因为这涉及在这种情况下与类行为不同的值类型。我知道关于 ++-- 也适用类似的规则,但我相信这个问题的背景足够不同,也足够细微,可以独立存在。

最佳答案

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?

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

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

C# 编译器不知道如何为您的类型执行该过程的唯一部分是“计算后继”,因此这是您重写的 ++ 运算符应该执行的操作。只返回继承者;让编译器处理如何进行分配。

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

是的,这样做。

关于c# - 为值类型实现 operator++ 的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34342513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com