Operator Overloading simplifies operations and makes operations more intuitive. However, compared with C ++, there are fewer operator sets that can be reloaded (it is strange that C ++ primer uses dozens of pages to discuss Operator overloading, which is a little too small. Why does this C # book only use one page ?). The following table lists the C # operators and their overloaded features.
| Operator |
Overload features |
| + -! ~ ++ -- True False |
Unary operators can be overloaded. |
| +-*/# & | ^ <> |
Binary operators can be reloaded. |
| = 1 = <> <=> = |
Comparison operators can be overloaded. |
| & | |
Cannot be overloaded |
| [] () |
Cannot be overloaded |
| + =-= Etc. |
Cannot be overloaded |
| = .?; -> New is as sizeof typeof |
Cannot be overloaded |
Note the following points:
- & | it cannot be directly overloaded, but it can be reloaded when it enters the calculation.
- [] cannot be overloaded. You can use the indexer to complete the required operations.
- () cannot be overloaded. Instead, the new conversion operator is defined.
- Compound operators cannot be overloaded because they are always broken down, for example, + =
- logical operators must be reloaded in pairs = and! =
below is a small example:
code highlighting produced by actipro codehighlighter (freeware)
http://www.CodeHighlighter.com/
--> Public static currency operator + (currency LHS, currency RHs)
{< br> return ( New currency (LHS. val + RHS. val);
}