Tài liệu Declaring Increment and Decrement Operators - Pdf 87



Declaring Increment and Decrement Operators
C# allows you to declare your own version of the increment (++) and decrement (––)
operators. The usual rules apply when declaring these operators; they must be public,
they must be static, and they must be unary. Here is the increment operator for the Hour
struct:
struct Hour
{
...
public static Hour operator++ (Hour arg)
{
arg.value++;
return arg;
}
...
private int value;
}
The increment and decrement operators are unique in that they can be used in prefix and
postfix forms. C# cleverly uses the same single operator for both the prefix and postfix
versions. The result of a postfix expression is the value of the operand before the
expression takes place. In other words, the compiler effectively converts this:
Hour now = new Hour(9);
Hour postfix = now++;
Into this:
Hour now = new Hour(9);
Hour postfix = now;
now = Hour.operator++(now); // pseudocode, not valid C#
The result of a prefix expression is the return value of the operator. The C# compiler
effectively converts this:
Hour now = new Hour(9);

return new Hour(arg.value + 1);
}
...
private int value;
}
Notice that operator++ now creates a new object based on the data in the original. The
data in the new object is incremented but the data in the original is left unchanged.
Although this works, the compiler translation of the increment operator results in a new
object being created each time it is used. This can be expensive in terms of memory use
and garbage collection overhead. Therefore, it is recommended that you limit operator
overloads when you define classes.


Nhờ tải bản gốc

Tài liệu, ebook tham khảo khác

Music ♫

Copyright: Tài liệu đại học © DMCA.com Protection Status