Does anyone have a very simple example of how to overload the compound assignment operator in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
You can't explicitly overload the compound assignment operators. You can however overload the main operator and the compiler expands it.
x += 1
is purely syntactic sugar forx = x + 1
and the latter is what it will be translated to. If you overload the+
operator it will be called.MSDN Operator Overloading Tutorial
You can't overload those operators in C#.
According to the C# specification, += is not in the list of overloadable operators. I assume, this is because it is an assignment operator as well, which are not allowed to get overloaded. However, unlike stated in other answers here, 'x += 1' is not the same as 'x = x + 1'. The C# specification, "7.17.2 Compound assignment" is very clear about that:
The important part is the last part: x is evaluated only once. So in situations like this:
it can (and does) make a difference, how to formulate your statement. But I assume, in most situations, the difference will negligible. (Even if I just came across one, where it is not.)
The answer to the question therefore is: one cannot override the += operator. For situations, where the intention is realizable via simple binary operators, one can override the + operator and archieve a similiar goal.