C# expressions and operators

C# expressions and operators

Expressions are widely used in C#, especially calculation functions, which often require a large number of expressions. Most expressions use operators, which combine one or more operands to form an expression and return the result of the operation.

1.1 Expression

Expressions are composed of operators and operands. For example, "+", "-", "/" and "*" are all operators, and the operands include text, constants, variables and expressions, etc. In C#, if the final calculation result of the expression is a value of the required type, the expression can appear anywhere that requires a value or object. The following is a simple console application that declares two variables, assigns initial values, and performs simple operations.

namespace Test01
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            int i = 92;                                                                                  //声明一个int类型的变量i并初始化为92
            int j = 11;                                                                                  //声明一个int类型的变量j并初始化为11
            Console.WriteLine(Math.Sin(i * i + j * j));                                           //表达式作为参数输出
            Console.ReadLine();
        }
    }
}

1.2 Operators

An operator is a special symbol mainly used in mathematical functions, some types of assignment statements, and logical comparison operations. C# provides a wealth of operators, such as arithmetic operators, assignment operators, comparison operators, etc.

1.2.1 Arithmetic operators

The "+", "-", "/", "*" and "%" operators are called arithmetic operators, which are used for addition, subtraction, division, multiplication, and modulo operations. Among them, the "+" and "-" operators can also be used as the positive and negative signs of the data. The following demonstrates how to make a simple calculator program.

 class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Console.Title = "简易计算器";//设置控制台标题
            Console.Write("输入第1个数字:");//提示用户输入第1个数值
            double d = double.Parse(Console.ReadLine());//得到第1个数值
            Console.Write("输入第2个数字:");//提示用户输入第2个数值
            double d2 = double.Parse(Console.ReadLine());//得到第2个数值
            Console.Write("输入第3个数字:");//提示用户输入第3个数值
            double d3 = double.Parse(Console.ReadLine());//得到第3个数值
            Console.WriteLine("加法计算结果:{0} + {1} + {2} = {3}", d, d2, d3, d + d2 +  d3);
            Console.WriteLine("减法计算结果:{0} - {1} - {2} = {3}", d, d2, d3, d - d2 -  d3);
            Console.WriteLine("乘法计算结果:{0} × {1} × {2} = {3}", d, d2, d3, d * d2 *  d3);
            Console.WriteLine("除法计算结果:{0} ÷ {1} ÷ {2} = {3}", d, d2, d3, d / d2 /  d3);
            Console.WriteLine("求余计算结果:{0} % {1} % {2} = {3}", d, d2, d3, d % d2 %  d3);
            Console.ReadLine();//等待回车继续
        }
    }

Note:
When arithmetic operators (+, -, /, *) are used for operations, the result may exceed the range of the value of the involved numeric type, which will lead to incorrect operation results; in addition, when performing division and calculation When performing remainder operations, the divisor must not be 0.

1.2.2 Increment and decrement operators

When using arithmetic operators, if you need to add 1 or subtract 1 to the value of a numeric variable. C# also provides self-increment and self-decrement operators, which are represented by ++ and –, such as a++, b–. If the program does not need to use the original value of the operand, but only needs to add (subtract) 1 to itself; then it is recommended to use pre-increment (subtraction), because the post-increment (subtraction) must save the original value, while the former Set auto-increment (subtraction) without saving the original value. At the same time, it is also necessary to explain here that the self-increment and self-decrement operations can only be applied to variables. Let me make a simple demonstration to explain

class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            int i = 1, j = 1;                             //定义int类型的变量
            int p_i, p_j;                                 //p_i表示后置形式运算的返回结果,p_j表示前置形式运算返回结果
            p_i = i++;                                    //后置形式的自增,p_i是1
            Console.WriteLine(i);                         //输出结果是2
            p_j = ++j;                                    //前置形式的自增,p_j是2
            Console.WriteLine(j);                         //输出结果是2
        }
    }

1.2.3 Assignment operation

Assignment operations assign new values ​​to elements such as variables, attributes, and events. Assignment operators mainly include "=" "+=" "-=" "*=" "/=" "%=" "&=" "|=" "^=" "<<=" ">>=" operator. The left side of the assignment operator must be an expression of variable, attribute access, indexer access, or event access type. If the types of operations on both sides of the assignment operator are inconsistent, type conversion must be performed first, and then the value should be assigned. Let me take the plus assignment (+=) operator as an example to make a simple demonstration

class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            int i = 92;                                                            //声明一个int类型的变量i并初始化为92
            i += 12;                                                       //使用加赋值运算符
            Console.WriteLine("最后i的值为:{0}", i);               //输出最后变量i的值
            Console.ReadLine();
        }
    }

1.2.4 Relational operators

Relational operators are binary operators used for comparisons between variables, between variables and independent variables, and between other types of information in a program. Relational operators return a Boolean value representing the result of the operation. When the relationship is established, the return result is true, otherwise the return result is false. Let me make a simple demonstration

class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            int num1 = 4, num2 = 7, num3 = 7;//定义3个int变量,并初始化
            //输出3个变量的值
            Console.WriteLine("num1=" + num1 + " , num2=" + num2 + " , num3=" + num3);
            Console.WriteLine();                                    //换行
            Console.WriteLine("num1<num2的结果:" + (num1 < num2)); //小于操作
            Console.WriteLine("num1>num2的结果:" + (num1 > num2)); //大于操作
            Console.WriteLine("num1==num2的结果:" + (num1 == num2));   //等于操作
            Console.WriteLine("num1!=num2的结果:" + (num1 != num2));   //不等于操作
            Console.WriteLine("num1<=num2的结果:" + (num1 <= num2));   //小于等于操作
            Console.WriteLine("num2>=num3的结果:" + (num2 >= num3));   //大于等于操作
            Console.ReadLine();
        }
    }

The result of the operation is as follows:

num1=4 , num2=7 , num3=7


num1<num2的结果:True
num1>num2的结果:False
num1==num2的结果:False
num1!=num2的结果:True
num1<=num2的结果:True
num2>=num3的结果:True

1.2.5 Logical operators

Expressions with a return type of Boolean can be combined to form more complex expressions using logical operators. The logical operators in C# mainly include "& (&&) (logical and)", "|| (logical or)" and "! (logical not)". The operands of logical operators must be bool type data. In logical operators, except "!" which is a unary operator, the others are binary operators. Variables or expressions whose result is bool type can be combined into logical expressions by logical operators.

1.2.6 Other special operators

1.is operator
is used to check whether the variable is the specified type. If yes, return true, otherwise return false. Let me make a simple demonstration

class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            int i = 1;                                                                            //声明整型变量i
            bool result = i is int;                                                               //判断i是否为整型
            Console.WriteLine(result);                                                            //输出结果
            Console.ReadLine();
        }
    }
}

The is operator cannot be overloaded. The is operator only considers reference conversions, boxing conversions, and unboxing conversions, not other conversions, such as user-defined conversions.
2. Conditional operator
The conditional operator (?:) returns one of two values ​​according to the value of a Boolean type expression. If the result is true, the first expression is calculated and its calculation result prevails, otherwise, the second expression prevails. The following is the expression format

条件式?1:值2

Let's do a simple demo

static void Main(string[] args)
        {
    
    
            Console.Write("请输入一个年份:");                                     //屏幕输入提示字符串
            string str = Console.ReadLine();                                       //获取用户输入的年份
            int year = Int32.Parse(str);                                                  //将输入的年份转换成int类型
            //计算输入的年份是否为闰年
            bool isleapyear = ((year % 400) == 0) || (((year % 4) == 0) && ((year % 100)  != 0));
            //利用条件运算符输入“是”或者“不是”
            string yesno = isleapyear ? "是" : "不是";
            Console.WriteLine("{0}年{1}闰年", year, yesno);                //输出结果
            Console.ReadLine();
        }

3. new operator
The new operator is used to create a new type instance, which has the following three forms.

  • An object creation expression used to create an instance of a class type or value type.
  • An array creation expression used to create an instance of an array type.
  • A delegate creation expression used to create a new instance of a delegate type.
    4. The typeof operator
    is used to obtain the type of the system prototype object, that is, the Type object. The Type class contains confidences about value types and reference types. The typeof operator can be used in various places in the C# language to find out about reference types and value types.

1.3 Operator precedence

An expression in C# is a formula that conforms to the C# specification and is connected by operators. The precedence of operators determines the order in which operations in an expression are performed. The order of priority from high to low is: increment and decrement operations→arithmetic operations→relational operations→assignment operations. The above is a summary of expressions and operators. I hope it will be useful for everyone to understand expressions and operators.

Guess you like

Origin blog.csdn.net/weixin_63284756/article/details/128509390