我正在研究Number结构的自定义实现,其存储和操作数值的方法非常不同。
该结构是完全不变的-所有字段都实现为 readonly
我正在尝试实现++
and--
运算符,但遇到了一些混乱:
如何执行分配?
还是平台会自动处理此问题,我只需要返回即可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;
}
}
编辑:我认为这不是关于增量和减量运算符的其他问题的重复,因为这涉及在这种情况下行为不同于类的值类型。我了解类似的规则适用于++
和--
,但是我相信这个问题的背景足以与众不同,足以独立存在。
该结构是完全不变的-所有字段都实现为
readonly
好的!
我正在尝试实现
++
and--
运算符,但遇到了一些混乱:如何执行分配?
你不知道 记住++
操作员的工作。无论是前缀还是后缀:
C#编译器不知道如何为您的类型执行此过程的唯一部分是“计算后继者”,因此这是您覆盖的++
运算符应执行的操作。只需退还继承人;让编译器弄清楚如何进行分配。
还是平台会自动处理此问题,我只需要返回即可
n + 1
?
是的,这样做。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句