📜  C#运算符

📅  最后修改于: 2020-10-06 09:35:20             🧑  作者: Mango

在本文中,我们将学习有关C#编程语言中不同类型的运算符以及如何使用它们的所有知识。

运算符是用于对操作数执行运算的符号。操作数可以是变量和/或常量。

例如 ,在2+3+是用于执行加法运算的运算符 ,而23是操作数。

运算符用于在程序中操纵变量和值。 C#支持许多运算符 ,这些运算符根据它们执行的操作类型进行分类。


1.基本分配运算符

基本赋值运算符 (=)用于为变量赋值。例如,

double x;
x = 50.05;

在此,将50.05分配给x。

示例1:基本分配运算符

using System;

namespace Operator
{
    class AssignmentOperator
    {
        public static void Main(string[] args)
        {
            int firstNumber, secondNumber;
            // Assigning a constant to variable
            firstNumber = 10;
            Console.WriteLine("First Number = {0}", firstNumber);

            // Assigning a variable to another variable
            secondNumber = firstNumber;
            Console.WriteLine("Second Number = {0}", secondNumber);
        }
    }
}

当我们运行程序时,输出将是:

First Number = 10
Second Number = 10

这是一个简单的示例,演示了赋值运算符的用法。

您可能已经注意到在示例中使用了大括号{ } 。我们将以字符串格式讨论它们。现在,请记住, {0}被字符串后面的第一个变量替换, {1}被第二个变量替换,依此类推。


2.算术运算符

算术运算运算符用于执行算术运算,例如加法,减法,乘法,除法等。

例如,

int x = 5;
int y = 10;
int z = x + y;// z = 15
C# Arithmetic Operators
Operator Operator Name Example
+ Addition Operator 6 + 3 evaluates to 9
Subtraction Operator 10 – 6 evaluates to 4
* Multiplication Operator 4 * 2 evaluates to 8
/ Division Operator 10 / 5 evaluates to 2
% Modulo Operator (Remainder) 16 % 3 evaluates to 1

示例2:算术运算符

using System;
 
namespace Operator
{
    class ArithmeticOperator
    {
        public static void Main(string[] args)
        {
            double firstNumber = 14.40, secondNumber = 4.60, result;
            int num1 = 26, num2 = 4, rem;

            // Addition operator
            result = firstNumber + secondNumber;
            Console.WriteLine("{0} + {1} = {2}", firstNumber, secondNumber, result);

            // Subtraction operator
            result = firstNumber - secondNumber;
            Console.WriteLine("{0} - {1} = {2}", firstNumber, secondNumber, result);

            // Multiplication operator
            result = firstNumber * secondNumber;
            Console.WriteLine("{0} * {1} = {2}", firstNumber, secondNumber, result);

            // Division operator
            result = firstNumber / secondNumber;
            Console.WriteLine("{0} / {1} = {2}", firstNumber, secondNumber, result);

            // Modulo operator
            rem = num1 % num2;
            Console.WriteLine("{0} % {1} = {2}", num1, num2, rem);
        }
    }
}

当我们运行程序时,输出将是:

14.4 + 4.6 = 19
14.4 - 4.6 = 9.8
14.4 * 4.6 = 66.24
14.4 / 4.6 = 3.1304347826087
26 % 4 = 2

在上面的示例中进行算术运算。变量可以用语句中的常量替换。例如,

result = 4.5 + 2.7 ; // result will hold 7.2
result = firstNumber - 3.2; // result will hold 11.2

3.关系运算符

关系运算符用于检查两个操作数之间的关系。如果关系为真,则结果为true ,否则为false

关系运算符用于决策和循环。

C# Relational Operators
Operator Operator Name Example
== Equal to 6 == 4 evaluates to false
> Greater than 3 > -1 evaluates to true
< Less than 5 < 3 evaluates to false
>= Greater than or equal to 4 >= 4 evaluates to true
<= Less than or equal to 5 <= 3 evaluates to false
!= Not equal to 10 != 2 evaluates to true

示例3:关系运算符

using System;
 
namespace Operator
{
    class RelationalOperator
    {
        public static void Main(string[] args)
        {
            bool result;
            int firstNumber = 10, secondNumber = 20;

            result = (firstNumber==secondNumber);
            Console.WriteLine("{0} == {1} returns {2}",firstNumber, secondNumber, result);

            result = (firstNumber > secondNumber);
            Console.WriteLine("{0} > {1} returns {2}",firstNumber, secondNumber, result);

            result = (firstNumber < secondNumber);
            Console.WriteLine("{0} < {1} returns {2}",firstNumber, secondNumber, result);

            result = (firstNumber >= secondNumber);
            Console.WriteLine("{0} >= {1} returns {2}",firstNumber, secondNumber, result);

            result = (firstNumber <= secondNumber);
            Console.WriteLine("{0} <= {1} returns {2}",firstNumber, secondNumber, result);

            result = (firstNumber != secondNumber);
            Console.WriteLine("{0} != {1} returns {2}",firstNumber, secondNumber, result);
        }
    }
}

当我们运行程序时,输出将是:

10 == 20 returns False
10 > 20 returns False
10 < 20 returns True
10 >= 20 returns False
10 <= 20 returns True
10 != 20 returns True

4.逻辑运算符

逻辑运算符用于执行逻辑运算,例如and or 。逻辑运算符对布尔表达式( truefalse )进行操作并返回布尔值。逻辑运算符用于决策和循环。

这是如何对逻辑ANDOR 运算符求值的结果。

C# Logical operators
Operand 1 Operand 2 OR (||) AND (&&)
true true true true
true false true false
false true true false
false false false false

简单来说,该表可以总结为:

  • 如果操作数之一为true,则OR 运算符会将其评估为true
  • 如果操作数之一为false,则AND 运算符会将其评估为false

示例4:逻辑运算符

using System;
 
namespace Operator
{
    class LogicalOperator
    {
        public static void Main(string[] args)
        {
            bool result;
            int firstNumber = 10, secondNumber = 20;

            // OR operator
            result = (firstNumber == secondNumber) || (firstNumber > 5);
            Console.WriteLine(result);

            // AND operator
            result = (firstNumber == secondNumber) && (firstNumber > 5);
            Console.WriteLine(result);
        }
    }
}

当我们运行程序时,输出将是:

True
False

5.一元运算符

与其他运算符不同,一元运算运算符对单个操作数进行运算。

C# unary operators
Operator Operator Name Description
+ Unary Plus Leaves the sign of operand as it is
Unary Minus Inverts the sign of operand
++ Increment Increment value by 1
Decrement Decrement value by 1
! Logical Negation (Not) Inverts the value of a boolean

示例5:一元运算符

using System;
 
namespace Operator
{
    class UnaryOperator
    {
        public static void Main(string[] args)
        {
            int number = 10, result;
            bool flag = true;

            result = +number;
            Console.WriteLine("+number = " + result);

            result = -number;
            Console.WriteLine("-number = " + result);

            result = ++number;
            Console.WriteLine("++number = " + result);

            result = --number;
            Console.WriteLine("--number = " + result);

            Console.WriteLine("!flag = " + (!flag));
        }
    }
}

当我们运行程序时,输出将是:

+number = 10
-number = -10
++number = 11
--number = 10
!flag = False

增量(++)和减量(--) 运算符可用作前缀和后缀。如果用作前缀,则变量的值更改将在同一行上显示;如果用作后缀,则变量的值更改将在下一行上显示。通过下面的示例将很清楚。

示例6:C#中的Post and Pre Increment 运算符

using System;
 
namespace Operator
{
    class UnaryOperator
    {
        public static void Main(string[] args)
        {
            int number = 10;

            Console.WriteLine((number++));
            Console.WriteLine((number));

            Console.WriteLine((++number));
            Console.WriteLine((number));
        }
    }
}

当我们运行程序时,输出将是:

10
11
12
12

我们可以看到使用++作为前缀和后缀的效果。在操作数之后使用++ ,将首先计算该值,然后将其递增1 。因此,声明

Console.WriteLine((number++));

打印10而不是11 。在打印值之后,数字的值将增加1

当将++用作前缀时,该过程相反。该值在打印前增加。因此,声明

Console.WriteLine((++number));

打印12

减数运算符 (--)的情况相同。


6.三元运算符

三元运算符 ? :对三个操作数进行运算。这是if-then-else语句的缩写。三元运算符可以按如下方式使用:

variable = Condition? Expression1 : Expression2;

三元运算符的工作方式如下:

  • 如果Condition表示的表达式为true ,则将Expression1的结果分配给变量。
  • 如果为false ,则将Expression2的结果分配给变量。

示例7:三元运算符

using System;
 
namespace Operator
{
    class TernaryOperator
    {
        public static void Main(string[] args)
        {
            int number = 10;
            string result;

            result = (number % 2 == 0)? "Even Number" : "Odd Number";
            Console.WriteLine("{0} is {1}", number, result);
        }
    }
}

当我们运行程序时,输出将是:

10 is Even Number

要了解更多信息,请访问C#三元运算符


7.按位和移位运算符

按位和移位运算符用于执行位操作。

C# Bitwise and Bit Shift operators
Operator Operator Name
~ Bitwise Complement
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Bitwise Left Shift
>> Bitwise Right Shift

例8:按位和移位操作

using System;
 
namespace Operator
{
    class BitOperator
    {
        public static void Main(string[] args)
        {
            int firstNumber = 10;
            int secondNumber = 20;
            int result;

            result = ~firstNumber;
            Console.WriteLine("~{0} = {1}", firstNumber, result);

            result = firstNumber & secondNumber;
            Console.WriteLine("{0} & {1} = {2}", firstNumber,secondNumber, result);

            result = firstNumber | secondNumber;
            Console.WriteLine("{0} | {1} = {2}", firstNumber,secondNumber, result);

            result = firstNumber ^ secondNumber;
            Console.WriteLine("{0} ^ {1} = {2}", firstNumber,secondNumber, result);

            result = firstNumber << 2;
            Console.WriteLine("{0} << 2 = {1}", firstNumber, result);

            result = firstNumber >> 2;
            Console.WriteLine("{0} >> 2 = {1}", firstNumber, result);
        }
    }
}

当我们运行程序时,输出将是:

~10 = -11
10 & 20 = 0
10 | 20 = 30
10 ^ 20 = 30
10 << 2 = 40
10 >> 2 = 2

要了解更多信息,请访问C#Bitwise和Bit Shift 运算符


8.复合赋值运算符
C# Compound Assignment Operators
Operator Operator Name Example Equivalent To
+= Addition Assignment x += 5 x = x + 5
-= Subtraction Assignment x -= 5 x = x - 5
*= Multiplication Assignment x *= 5 x = x * 5
/= Division Assignment x /= 5 x = x / 5
%= Modulo Assignment x %= 5 x = x % 5
&= Bitwise AND Assignment x &= 5 x = x & 5
|= Bitwise OR Assignment x |= 5 x = x | 5
^= Bitwise XOR Assignment x ^= 5 x = x ^ 5
<<= Left Shift Assignment x <<= 5 x = x << 5
>>= Right Shift Assignment x >>= 5 x = x >> 5
=> Lambda Operator x => x*x Returns x*x

示例9:复合赋值运算符

using System;
 
namespace Operator
{
    class BitOperator
    {
        public static void Main(string[] args)
        {
            int number = 10;

            number += 5;
            Console.WriteLine(number);

            number -= 3;
            Console.WriteLine(number);

            number *= 2;
            Console.WriteLine(number);

            number /= 3;
            Console.WriteLine(number);

            number %= 3;
            Console.WriteLine(number);

            number &= 10;
            Console.WriteLine(number);

            number |= 14;
            Console.WriteLine(number);

            number ^= 12;
            Console.WriteLine(number);

            number <<= 2;
            Console.WriteLine(number);

            number >>= 3;
            Console.WriteLine(number);
        }
    }
}

当我们运行程序时,输出将是:

15
12
24
8
2
2
14
2
8
1

我们将在后面的教程中讨论Lambda 运算符