Operators
Category |
Operator |
---|---|
Arithmetic |
+ – * / % |
Logical |
& | ^ ~ && || ! |
String concatenation |
+ |
Increment and decrement |
++ — |
Bit shifting |
<< >> |
Comparison |
== != < > <= >= |
Assignment |
= += -= *= /= %= &= |= ^= <<= >>= |
Member access (for objects and structs) |
. |
Indexing (for arrays and indexers) |
[] |
Cast |
() |
Conditional (the Ternary Operator) |
?: |
Object Creation |
new |
Type information |
sizeof (unsafe code only) is typeof as |
Overflow exception control |
checked unchecked |
Indirection and Address |
* –> & (unsafe code only) [] |
Câu sau đây có nghĩa là x bằng với 3:
x = 3;
Nếu chúng ta muốn so sánh x với một giá trị chúng ta sử dụng kí hiệu sau ==:
if (x == 3)
Operator Shortcuts
Bảng dưới đây trình bày một danh sách đầy đủ của shortcut operators có giá trị trong C#:
Shortcut Operator |
Tương đương |
---|---|
x++, ++x |
x = x + 1 |
x–, –x |
x = x – 1 |
x += y |
x = x + y |
x -= y |
x = x – y |
x *= y |
x = x * y |
x /= y |
x = x / y |
x %= y |
x = x % y |
x >>= y |
x = x >> y |
x <<= y |
x = x << y |
x &= y |
x = x & y |
x |= y |
x = x | y |
x ^= y |
x = x ^ y |
Thí dụ :
int x = 5;
if (++x == 6)
{
Console.WriteLine(“This will execute”);
}
if (x++ == 7)
{
Console.WriteLine(“This won’t”);
}
x += 5;
x = x + 5;
The Ternary Operator
Cú pháp :
condition ? true_value : false_value
Thí dụ :
int x = 1;
string s = x.ToString() + ” “;
s += (x == 1 ? “man” : “men”);
Console.WriteLine(s);
is
int i = 10;
if (i is object)
{
Console.WriteLine(“i is an object”);
}
sizeof
string s = “A string”;
unsafe
{
Console.WriteLine(sizeof(int));
}
Operator Precedence
Group |
Operators |
---|---|
() . [] x++ x– new typeof sizeof checked unchecked |
|
Unary |
+ – ! ~ ++x –x and casts |
Multiplication/Division |
* / % |
Addition/Subtraction |
+ – |
Bitwise shift operators |
<< >> |
Relational |
< > <= >= is as |
Comparison |
== != |
Bitwise AND |
& |
Bitwise XOR |
^ |
Bitwise OR |
| |
Boolean AND |
&& |
Boolean OR |
|| |
Ternary operator |
?: |
Assignment |
= += -= *= /= %= &= |= ^= <<= >>= >>>= |