Tải bản đầy đủ (.pdf) (1 trang)

Understanding Compound Assignment

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (6.94 KB, 1 trang )



Understanding Compound Assignment
C# does not allow you to declare any user-defined assignment operators. However, a
compound assignment operator (such as +=) is always evaluated in terms of its associated
operator (such as +). In other words, this:
a += b;
Is automatically evaluated as this:
a = a + b;
In general, the expression a @= b (where @ represents any valid operator) is always
evaluated as a = a @ b. If you have declared the appropriate simple operator, it is
automatically called when you use its associated compound assignment operator. For
example:
Hour a = ...;
int b = ...;
a += a; // same as a = a + a
a += b; // same as a = a + b
The first compound assignment expression (a += a) is valid because a is of type Hour,
and the Hour type declares a binary operator+ whose parameters are both Hour.
Similarly, the second compound assignment expression (a += b) is also valid because a is
of type Hour and b is of type int. The Hour type also declares a binary operator+ whose
first parameter is an Hour and whose second parameter is an int. Note, however, that you
cannot write the expression b += a because that's the same as b = b + a. Although the
addition is valid, the assignment is not because there is no way to assign an Hour to the
built-in int type.



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×