Home > Backend Development > C#.Net Tutorial > [c# tutorial] C# operators

[c# tutorial] C# operators

黄舟
Release: 2016-12-26 14:11:46
Original
1075 people have browsed it

C# Operator The

operator is a symbol that tells the compiler to perform a specific mathematical or logical operation. C# has a rich set of built-in operators, which are classified as follows:

Arithmetic operators

Relational operators

Logical operators

Bitwise operators

Assignment Operators

Miscellaneous Operators

This tutorial will explain arithmetic operators, relational operators, logical operators, bitwise operators, assignment operators and other operators one by one.

Arithmetic operators

The following table shows all the arithmetic operators supported by C#. Assume that the value of variable A is 10 and the value of variable B is 20, then:

Operator

Description

Instance

+ Adding the two operands A + B will get 30

- Subtracting the second operand A - B from the first operand will get -10

* Multiply the two operands A * B will get 200

/ Divide the numerator by the denominator B / A will get 2

% Modulo operator, after integer division The remainder of B % A will get 0

++ Increment operator, the integer value increases by 1 A++ will get 11

-- Decrement operator, the integer value decreases by 1 A-- will Get 9

Example

Look at the following example to learn about all the arithmetic operators available in C#:

using System;

namespace OperatorsAppl
{
class Program
{
  static void Main(string[] args)
      {
            int a = 21;
              int b = 10;
                int c;

            c = a + b;
            Console.WriteLine("Line 1 - The value of c is {0}", c); "Line 2 - The value of c is {0}", c);
        c = a * b;
        Console.WriteLine("Line 3 - The value of c is {0}", c);
                     c = a / b;
              Console.WriteLine("Line 4 - The value of c is {0}", c);
         c = a % b;
             Console.WriteLine("("Line 5 -" The value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - The value of c is {0}", c);
c = a-- ;
          Console.WriteLine("Line 7 - The value of c is {0}", c);
            Console.ReadLine();
      }
    }
}


When the above code is compiled and executed, it produces the following results:

Line 1 - The value of c is 31

Line 2 - The value of c is 11

Line 3 - The value of c is 210
Line 4 - The value of c is 2
Line 5 - The value of c is 1
Line 6 - The value of c is 21
Line 7 - The value of c is 22


Relational Operators

The following table shows all the relational operators supported by C#. Assume that the value of variable A is 10 and the value of variable B is 20, then:

Operator

Description

Instance

== Checks whether the values ​​of the two operands are equal. If they are equal, the condition is true. (A == B) is not true.

!= Checks whether the values ​​of the two operands are equal. If they are not equal, the condition is true. (A != B) is true.

> Check whether the value of the left operand is greater than the value of the right operand, if so, the condition is true. (A > B) is not true.

< Check whether the value of the left operand is less than the value of the right operand, if so, the condition is true. (A < B) is true.

>= Checks whether the value of the left operand is greater than or equal to the value of the right operand. If so, the condition is true. (A >= B) is not true.

<= Check whether the value of the left operand is less than or equal to the value of the right operand, if so, the condition is true. (A <= B) is true.

Examples

Look at the following examples to learn about all the relational operators available in C#:

using System;

class Program
{
  static void Main(string[] args)
  {
      int a = 21;
      int b = 10;
      
      if (a == b)
      {
          Console.WriteLine("Line 1 - a 等于 b");
      }
      else
      {
          Console.WriteLine("Line 1 - a 不等于 b");
      }
      if (a < b)
      {
          Console.WriteLine("Line 2 - a 小于 b");
      }
      else
      {
          Console.WriteLine("Line 2 - a 不小于 b");
      }
      if (a > b)
      {
          Console.WriteLine("Line 3 - a 大于 b");
      }
      else
      {
          Console.WriteLine("Line 3 - a 不大于 b");
      }
      /* 改变 a 和 b 的值 */
      a = 5;
      b = 20;
      if (a <= b)
      {
         Console.WriteLine("Line 4 - a 小于或等于 b");
      }
      if (b >= a)
      {
         Console.WriteLine("Line 5 - b 大于或等于 a");
      }
  }
}
Copy after login

When the above code is compiled and executed, it produces the following Result:

Line 1 - a 不等于 b
Line 2 - a 不小于 b
Line 3 - a 大于 b
Line 4 - a 小于或等于 b
Line 5 - b 大于或等于 a
Copy after login

Logical operators

The following table shows all the logical operators supported by C#. Assume that variable A is a Boolean value true and variable B is a Boolean value false, then:

Operator

Description

Instance

&& is called the logical AND operator. The condition is true if both operands are non-zero. (A && B) is false.

|| is called the logical OR operator. The condition is true if either of the two operands is non-zero. (A || B) is true.

! is called the logical NOT operator. Used to reverse the logical state of the operand. The logical NOT operator will make the condition false if it is true. !(A && B) is true.

Example

Look at the following example to learn about all the logical operators available in C#:

using System;

namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            bool a = true;
            bool b = true;
           
            if (a && b)
            {
               Console.WriteLine("Line 1 - 条件为真");
            }
            if (a || b)
            {
                Console.WriteLine("Line 2 - 条件为真");
            }
            /* 改变 a 和 b 的值 */
            a = false;
            b = true;
            if (a && b)
            {
                Console.WriteLine("Line 3 - 条件为真");
            }
            else
            {
                Console.WriteLine("Line 3 - 条件不为真");
            }
            if (!(a && b))
            {
                Console.WriteLine("Line 4 - 条件为真");
            }
            Console.ReadLine();
        }
    }
}
Copy after login

When the above code is compiled and executed, it produces the following Result:

Line 1 - 条件为真
Line 2 - 条件为真
Line 3 - 条件不为真
Line 4 - 条件为真
Copy after login

Bitwise Operators

Bitwise operators act on bits and perform operations bit by bit. The truth table for &, | and ^ is as follows:

p

q

p & q

p | q

p ^ q

0 0 0 0 0 0

0 1 0 1 1 1

1 1 1 1 1 0

1 0 0 1 1

Suppose if A = 60, and B = 13, now expressed in binary format, they are as follows:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The following table lists the bitwise operators supported by C#. Assume that the value of variable A is 60 and the value of variable B is 13, then:

Operator

Description

Instance

& If present in both operands, the binary AND operator copies one bit to the result. (A & B) will give 12, which is 0000 1100

| If present in either operand, the binary OR operator copies one bit to the result. (A | B) will get 61, which is 0011 1101

^ If it exists in one of the operands but not both, the binary XOR operator copies one bit to the result . (A ^ B) will get 49, which is 0011 0001

~ The two's complement operator is a unary operator and has the effect of "flipping" bits. (~A) will get -61, which is 1100 0011, 2's complement, signed binary number.

<< Binary left shift operator. The value of the left operand is shifted left by the number of bits specified by the right operand. A << 2 will get 240, which is 1111 0000

>> Binary right shift operator. The value of the left operand is shifted to the right by the number of bits specified by the right operand. A >> 2 will get 15, which is 0000 1111

Example

Please see the following example to learn about all the bitwise operators available in C#:

using System;
namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 60;	           /* 60 = 0011 1100 */  
            int b = 13;	           /* 13 = 0000 1101 */
            int c = 0;           

             c = a & b;           /* 12 = 0000 1100 */ 
             Console.WriteLine("Line 1 - c 的值是 {0}", c );

             c = a | b;           /* 61 = 0011 1101 */
             Console.WriteLine("Line 2 - c 的值是 {0}", c);

             c = a ^ b;           /* 49 = 0011 0001 */
             Console.WriteLine("Line 3 - c 的值是 {0}", c);

             c = ~a;               /*-61 = 1100 0011 */
             Console.WriteLine("Line 4 - c 的值是 {0}", c);

             c = a << 2;     /* 240 = 1111 0000 */
             Console.WriteLine("Line 5 - c 的值是 {0}", c);

             c = a >> 2;     /* 15 = 0000 1111 */
             Console.WriteLine("Line 6 - c 的值是 {0}", c);
            Console.ReadLine();
        }
    }
}
Copy after login

When the above code is compiled and executed, it produces the following results:

Line 1 - c 的值是 12
Line 2 - c 的值是 61
Line 3 - c 的值是 49
Line 4 - c 的值是 -61
Line 5 - c 的值是 240
Line 6 - c 的值是 15
Copy after login

Assignment Operators

The following table lists the assignment operators supported by C#:

Operator

Description

Instance

= 简单的赋值运算符,把右边操作数的值赋给左边操作数 C = A + B 将把 A + B 的值赋给 C

+= 加且赋值运算符,把右边操作数加上左边操作数的结果赋值给左边操作数 C += A 相当于 C = C + A

-= 减且赋值运算符,把左边操作数减去右边操作数的结果赋值给左边操作数 C -= A 相当于 C = C - A

*= 乘且赋值运算符,把右边操作数乘以左边操作数的结果赋值给左边操作数 C *= A 相当于 C = C * A

/= 除且赋值运算符,把左边操作数除以右边操作数的结果赋值给左边操作数 C /= A 相当于 C = C / A

%= 求模且赋值运算符,求两个操作数的模赋值给左边操作数 C %= A 相当于 C = C % A

<<= 左移且赋值运算符 C <<= 2 等同于 C = C << 2

>>= 右移且赋值运算符 C >>= 2 等同于 C = C >> 2

&= 按位与且赋值运算符 C &= 2 等同于 C = C & 2

^= 按位异或且赋值运算符 C ^= 2 等同于 C = C ^ 2

|= 按位或且赋值运算符 C |= 2 等同于 C = C | 2

实例

请看下面的实例,了解 C# 中所有可用的赋值运算符:

using System;

namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 21;
            int c;

            c = a;
            Console.WriteLine("Line 1 - =  c 的值 = {0}", c);

            c += a;
            Console.WriteLine("Line 2 - += c 的值 = {0}", c);

            c -= a;
            Console.WriteLine("Line 3 - -=  c 的值 = {0}", c);

            c *= a;
            Console.WriteLine("Line 4 - *=  c 的值 = {0}", c);

            c /= a;
            Console.WriteLine("Line 5 - /=  c 的值 = {0}", c);

            c = 200;
            c %= a;
            Console.WriteLine("Line 6 - %=  c 的值 = {0}", c);

            c <<= 2;
            Console.WriteLine("Line 7 - <<=  c 的值 = {0}", c);

            c >>= 2;
            Console.WriteLine("Line 8 - >>=  c 的值 = {0}", c);

            c &= 2;
            Console.WriteLine("Line 9 - &=  c 的值 = {0}", c);

            c ^= 2;
            Console.WriteLine("Line 10 - ^=  c 的值 = {0}", c);

            c |= 2;
            Console.WriteLine("Line 11 - |=  c 的值 = {0}", c);
            Console.ReadLine();
        }
    }
}
Copy after login

当上面的代码被编译和执行时,它会产生下列结果:

Line 1 - =     c 的值 = 21
Line 2 - +=    c 的值 = 42
Line 3 - -=    c 的值 = 21
Line 4 - *=    c 的值 = 441
Line 5 - /=    c 的值 = 21
Line 6 - %=    c 的值 = 11
Line 7 - <<=    c 的值 = 44
Line 8 - >>=    c 的值 = 11
Line 9 - &=    c 的值 = 2
Line 10 - ^=    c 的值 = 0
Line 11 - |=    c 的值 = 2
Copy after login

杂项运算符

下表列出了 C# 支持的其他一些重要的运算符,包括 sizeof、typeof 和 ? :。

运算符描述实例 sizeof()返回数据类型的大小。sizeof(int),将返回 4. typeof()返回 class 的类型。typeof(StreamReader); &返回变量的地址。&a; 将得到变量的实际地址。 *变量的指针。*a; 将指向一个变量。 ? :条件表达式 如果条件为真 ? 则为 X : 否则为 Y is判断对象是否为某一类型。If( Ford is Car) // 检查 Ford 是否是 Car 类的一个对象。 as强制转换,即使转换失败也不会抛出异常。Object obj = new StringReader("Hello");
StringReader r = obj as StringReader;

实例

using System;

namespace OperatorsAppl
{
    
   class Program
   {
      static void Main(string[] args)
      {
         
         /* sizeof 运算符的实例 */
         Console.WriteLine("int 的大小是 {0}", sizeof(int));
         Console.WriteLine("short 的大小是 {0}", sizeof(short));
         Console.WriteLine("double 的大小是 {0}", sizeof(double));
         
         /* 三元运算符符的实例 */
         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("b 的值是 {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("b 的值是 {0}", b);
         Console.ReadLine();
      }
   }
Copy after login

当上面的代码被编译和执行时,它会产生下列结果:

int 的大小是 4
short 的大小是 2
double 的大小是 8
b 的值是 30
b 的值是 20
Copy after login

C# 中的运算符优先级

运算符的优先级确定表达式中项的组合。这会影响到一个表达式如何计算。某些运算符比其他运算符有更高的优先级,例如,乘除运算符具有比加减运算符更高的优先级。

例如 x = 7 + 3 * 2,在这里,x 被赋值为 13,而不是 20,因为运算符 * 具有比 + 更高的优先级,所以首先计算乘法 3*2,然后再加上 7。

下表将按运算符优先级从高到低列出各个运算符,具有较高优先级的运算符出现在表格的上面,具有较低优先级的运算符出现在表格的下面。在表达式中,较高优先级的运算符会优先被计算。

类别

运算符

结合性

后缀 () [] -> . ++ - - 从左到右

一元 + - ! ~ ++ - - (type)* & sizeof 从右到左

乘除 * / % 从左到右

加减 + - 从左到右

移位 << >> 从左到右

关系 < <= > >= 从左到右

相等 == != 从左到右

位与 AND & 从左到右

位异或 XOR ^ 从左到右

位或 OR | 从左到右

逻辑与 AND && 从左到右

逻辑或 OR || 从左到右

条件 ?: 从右到左

赋值 = += -= *= /= %=>>= <<= &= ^= |= 从右到左

逗号 , 从左到右

实例

using System;

namespace OperatorsAppl
{
    
   class Program
   {
      static void Main(string[] args)
      {
         int a = 20;
         int b = 10;
         int c = 15;
         int d = 5;
         int e;
         e = (a + b) * c / d;     // ( 30 * 15 ) / 5
         Console.WriteLine("(a + b) * c / d 的值是 {0}", e);

         e = ((a + b) * c) / d;   // (30 * 15 ) / 5
         Console.WriteLine("((a + b) * c) / d 的值是 {0}", e);

         e = (a + b) * (c / d);   // (30) * (15/5)
         Console.WriteLine("(a + b) * (c / d) 的值是 {0}", e);

         e = a + (b * c) / d;    //  20 + (150/5)
         Console.WriteLine("a + (b * c) / d 的值是 {0}", e);
         Console.ReadLine();
      }
   }
}
Copy after login

当上面的代码被编译和执行时,它会产生下列结果:

(a + b) * c / d 的值是 90
((a + b) * c) / d 的值是 90
(a + b) * (c / d) 的值是 90
a + (b * c) / d 的值是 50
Copy after login

 以上就是【c#教程】C# 运算符的内容,更多相关内容请关注PHP中文网(www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template