问题描述
我只是在重载增量运算符.我希望既有增量又有增量.不幸的是,我看到无论操作员处于前置位置还是后置位置,都调用了相同的方法.因此,我检查了规格并惊讶地发现:
"
请注意,运算符返回通过将1加到操作数而产生的值,就像后缀递增和递减运算符(第7.5.9节) ,以及前缀递增和递减运算符(第7.6.5节),与C ++不同,此方法不需要,实际上也不必直接修改其操作数的值.
"
没有增量的增量运算符有什么用呢?如果我想做x += 1
,我有加法运算符,它工作得很好.我想要x++
和 ++x
,就像内置数字类型一样; x = x++
或x = ++x
将是荒谬的,但看来我们只允许这样做.
我错过了什么吗?有没有人可以解决?
P.S.还是只是00:34,我应该去睡觉了?它似乎以预期的方式工作了吗? [confused]
I was just working on overloading the increment operator. I was hoping to have both pre-increment and post-increment. Unfortunately I see that the same method is called regardless of whether the operator is in pre- or post-position. So I checked the spec and was surprised to find:
"
Note that the operator returns the value produced by adding 1 to the operand, just like the postfix increment and decrement operators (§7.5.9), and the prefix increment and decrement operators (§7.6.5). Unlike in C++, this method need not, and, in fact, must not, modify the value of its operand directly.
"
What the heck good is an increment operator that doesn''t increment?! If I want to do x += 1
I have the addition operator for that and it works just fine. I want x++
and ++x
just like with the built-in numeric types; x = x++
or x = ++x
would be ridiculous, but it appears that''s all we''re allowed.
Am I missing something? Does anyone have a work-around?
P.S. Or is just that it''s 00:34 and I should go get some sleep? It seems to be working as expected somehow? [confused]
推荐答案
public class IntWrapper
{
public int IntValue
{
get;
set;
}
}
而且我们想像这样使用它
and we want to use it like this
IntWrapper a = new IntWrapper();
IntWrapper b = a;
a++;
Console.WriteLine("a = {0}, b = {1}", a.IntValue, b.IntValue);
这是我们类中增量运算符重载的两种可能的实现,第二种是正确的方法
Here are two possible implementations for the increment operator overload in our class, the second is the correct way
public static IntWrapper operator ++(IntWrapper instance)
{
// WRONG! a and b will be incremented
instance.IntValue++;
return instance;
}
public static IntWrapper operator ++(IntWrapper instance)
{
// CORRECT! Only a will be incremented
IntWrapper result = new IntWrapper();
result.IntValue = instance.IntValue + 1;
return result;
}
这篇关于重载增量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!