C# basic learning (1)

1. C# language concept and its characteristics

1) concept

C# 是微软发布的一种面向对象的、运行于 .NET Framework 和 .NET Core(完全开源,跨平台) 之上的高级程序设计语言;
C# is a safe, stable, simple, and elegant object-oriented programming language derived from C and C++. 它在继承C和C++强大功能的同时去掉了一些它们的复杂特性;

2) The difference between object-oriented and process-oriented programming languages:

面向过程: is one 以过程为中心的编程思想. It is 一种基础的顺序思维方式,是以什么正在发生为主要目标进行编程different from object-oriented who is affected;:
特性: 模块化、流程化;
常见的 面向过程编程语言有( C语言、COBOL 语言、Fortran语言 等。advantages: performance is higher than object-oriented, object-oriented class calls need to be instantiated and consume resources)

面向对象:is one of a kind 对现实世界理解和抽象的方法,是计算机编程技术发展到一定阶段后的产物. It directly treats all things as independent objects. In the process of dealing with the problem, the main consideration is no longer how to use the data structure to describe the problem, but to directly consider the relationship between the various objects in the problem. (The basic implementation of the object-oriented method also includes process-oriented thinking); ;
特性: 抽象封装继承多态:
常见的支持面向对象的编程语言有( C++ 语言、C# 语言、Java 语言、Python等。Advantages: it has the characteristics of encapsulation, inheritance, and polymorphism, so it is easy to maintain, reuse, and expand)

3) Know .NET Framework & .NET Core

NET and C# relationship:

.NET是平台;
C# is an object applicable to the platform, C# 只能运行在.NET 平台but the .NET platform can also adapt to other objects, such as C++, VB, etc.

NET Framework and .NET Core:

.Net FrameworkThe history is .Net Core longer. The first version of .Net Framework was launched around 2002, while the first version of .Net Core was launched around 2016, with a difference of nearly 14 years; ,
.Net Framework; 只针对Windows平台,包含了Windows平台的所有特性but .Net Core 可以针对多个平台发布,但是.Net Core 无法包含.Net Framework的所有特性。.Net Core的跨平台特性可以方便的在多个平台上共享业务逻辑。

4) C# powerful programming function

Although C#的构想十分接近于传统的高级语言C和C++it is a discipline 面向对象的编程语言, 它与JAVA非常相似,有很大强大的编程功能it is favored by the majority of programmers.
Some important features of C# are listed below:

  • Boolean Condition (Boolean Condition)
  • Automatic Garbage Collection
  • Standard Library
  • Assembly Versioning
  • Properties and Events
  • Delegates and Events Management
  • Generics for ease of use
  • Indexers
  • Conditional Compilation
  • Simple multithreading (Multithreading)
  • LINQ and Lambda Expressions Integration Windows

5) C# Integrated Development Environment (Integrated Development Environment - IDE)

Microsoft provides the following for C#编程的工具:

  • Visual Studio 2022(VS)
  • Visual C# 2022 Express(VCE)
  • Visual Web Developer

The latter two are free to use and can be downloaded from Microsoft's official website. Visual C# 2022 Express and Visual Web Developer editions are customized versions of Visual Studio with the same look and feel. They retain most of the functionality of Visual Studio.

6) Write C# programs on Linux or Mac OS

Although .NET 框架it runs on Windows Windows操作系统上, there are also versions that run on other operating systems. Mono 是.NET框架的一个开源版本,它包含了一个C#编译器, 且可运行于多种操作系统上, such as various versions of Linux and Mac OS. To learn more, you can visit Go Mono.
The purpose of Mono is not only to run Microsoft's .NET applications across platforms, but also to provide better development tools for Linux developers.Mono 可运行在多种操作系统上, 包括Android 、BSD 、iOS、Linux、 OS X、 Windows、 Solaris 和UNIX。

2. C# program structure

C# Hello World example

A C# program mainly includes the following parts:

  • Namespace (Namespace declaration) ·
  • A class Class method
  • Class attribute
  • a Main method
  • Statement (Statement) & Expression (Expressions)
  • Annotate C#
  • The suffix of the file is **.cs**

The following creates a test.cs file that contains simple code that prints "hello world":

using System;
namespace HelloWorldApplication
{
    
    
    class HelloWorld
    {
    
    
        static void Main(sting[] args)
        {
    
    
            /*我的第一个C#程序*/
            Console.WriteLine("hello world");
            Console.ReadKey();
        }
    }
}

insert image description here

When the above code is compiled and executed, the result is as follows:

insert image description here

Let's look at the various parts of the program above:

  • The first line of the program using System; using关键字用于在程序中包含System的命名空间. 一个程序可以有多个using, which includes multiple command spaces (similar to #include<stido.h> from the language)
  • The next line is namespacethe statement. A namespace contains a series of classes. HelloWorldApplicationThe namespace contains the 类HelloWorld.
  • The next line is the class declaration.
    类HelloWorldContains the ones used by the program 数据和方法声明. 类一般包含多个方法,方法定义了类的行为。Here the HelloWorld class 只有一个方法Main.
  • The next line defines Main方法, 是所有C#程序的入口点. The Main method specifies what actions the class will do when executed.
  • The next line /…/ is a comment and will be ignored by the compiler.
  • The Main method specifies its behavior through the statement Console.WriteLine("hello world");
    WriteLineYes, 一个定义在System命名空间中的Console类的一个方法。this statement will display the message "hello World" on the screen.
  • The last line Console.ReadKey(); is for VS.NETthe user. This makes the program wait for a key press,防止程序从Visual Studio .NET启动时屏幕会快速运行并关闭。

The following points need attention:

  • C# case sensitive
  • All statements and expressions must end with a semicolon (;)
  • The program starts with the Main method
  • Unlike Java, the filename can be different from the name of the class

Compile & execute C# program

如果您使用Visual Studio .NET编译和执行C#程序,请按照下面的步骤操作

  • Start Visual Studio On the menu bar, select File -> New -> Project Select Visual
    C# from Templates,
  • Then select Windows Select Console Application Give your project a name
  • Then click the OK button, and the new project will appear in the Solution Explorer (Solution Explorer).
  • Write code in the Code Editor
  • Click the Run button or press the F5 key to run the program
  • A command prompt window (Command Promotion Windows) will appear, displaying hello World

您也可以使用命令行代替Visual Studio IDE来编译C#程序:

  • Open a text editor and add the above code
  • Save the file as HelloWorld.cs
  • Open the command prompt tool and navigate to the directory where the file is saved
  • Type csc helloworld.cs and press enter to compile the code
  • If there are no errors in the code, the command line prompt goes to the next line and generates the HelloWorld.ext executable
  • Next, type helloworld to execute the program
  • You will see "hello World" displayed on the screen

3. Basic syntax of C#

Take the Rectangle (rectangle) object as an example, it has length and width attributes, according to which the area can be calculated. Let's explain the basic syntax of C# with the implementation of a Rectangle class:

using System;
namespace RectangleApplication
{
    
    
    class Rectangle
    {
    
    
        //成员变量
        double length;
        double width;
        public void Acceptdetails()
        {
    
    
            length = 4;
            width = 3;
        }
        public double GetArea()
        {
    
    
            return length * width;
        }
        public void Display()
        {
    
    
            Console.WriteLine("length:{0}", length);
            Console.WriteLine("width:{0}", width);
            Console.WriteLine("Area:[0}", GetArea());
        }
    }
   class ExecuteRectangle
    {
    
    
        static void Main(string[] args)
        {
    
    
            Reatangle r = new Rectangle();
            r.Acceptdetails();
            r.Display();
            Console.ReadLine();
        }
    }
}

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

length: 4
width: 3
Area: 12

using keyword

The first statement in any C# program is:

using System;
// using System;
 
namespace ConsoleApp1
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            System.String a = "Hello World!";
            System.Console.WriteLine(a);
            System.Console.ReadKey();
        }
    }
}
using System;
 
namespace ConsoleApp1
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            string a = "Hello World!";
            Console.WriteLine(a);
            Console.ReadKey();
        }
    }
}

are equivalent.
The using keyword is used to include a namespace in a program.一个程序可以包含多个 using 语句

class keyword

The class keyword is used to declare a class

Comments in C#

Comments are used to explain code. The compiler ignores commented entries. In a C# program, use /* XXXXX */ for multi-line comments, as shown below:

/*This program demonstrates 
The basic sysntax of C# programming
Language */

Single-line comments are represented by the "//" symbol. For example:

Member variables

变量是类的属性or 数据成员, for 存储数据. In the above program, the Rectangle class has two member variables named length and width.

member function

A function is a series of statements that perform a specified task. 类的成员函数是在类内声明的. Our example class Rectangle contains three member functions: AcceptDetails, GetAreaand Display.

Instantiate a class
In the program above, 类ExecuteRectangleyes 一个包含Main() 方法和实例化Rectangle类的类.

identifier

标识符is used to identify a class, variable, function, or any other user-defined item. In C#, the naming of classes must obey the following basic rules:

  • 标识符必须以字母、下划线或 @ 开头,后面可以跟一系列的字母、数字(0-9)、下划线(_)、@
  • Identifier No.一个字符不能是数字
  • The identifier must不包含任何嵌入的空格或符号,比如?-+!%……&*()[ ] { } . ; :" ’ / \
  • 标识符不能是C#的关键字. Unless they have an @ prefix. .For example, @if is a valid identifier, but if is not, because if is a keyword
  • 标识符必须区分大小写. Uppercase and lowercase letters are considered different letters
  • 不能与C#的类库名称相同

C# keywords

关键字yes C#编译器预定义的保留字. These keywords cannot be used as identifiers, however, 如果想使用这些关键字作为标识符,可以在关键字前面加上@字符作为前缀
in C# some keywords have special meaning in the context of the code. eg get和set,这些被称为上下文关键字. The following table lists the reserved and contextual keywords in C#:

保留关键字
abstract as base bool break byte case
catch char checked class const continue decimal
default delegate do double else enum event
explict extern false finally fixed float for
foreach goto if implict in in(generic modifier) int
interface internal is lock long namespace new
null object operator out out(generic modifier) override params
private protected public readonly ref return sbyte
sealed short sizeof stackalloc static string struct
switch this throw true try typeof uint
ulong unchecked unsafe ushort using virtual void
volatile while
上下文关键字
add alias ascending descending dynamic from
global group into join let orderby
partial(method) remove select set

C# data types

In C#, variables are divided into the following types:

  • Values ​​type
  • Reference types
  • Pointer types
  • Values ​​types
  • Value type variables can be directly assigned to a value, they are System.ValueTypederived from the class.
    值类型直接包含数据. Such as int, char, float, they are stored separately 数字,字符、浮点数. When you declare an int type, the system allocates the memory class to store the value.
    The following table lists the value types available in C#2010:
    insert image description here
    To get the exact size of a type or a variable on a specific platform, use the sizeof method. The expression sizeof(type) yields the storage size in bytes of the stored object or type. The following example obtains the storage size of int type on any machine:
using System;
namespace DataTypeApplication
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            Console.WriteLine("Size of int:{0}", sizeof(int));
            Console.ReadLine();
        }
    }    
}
Size of int: 4

Reference types

Reference types do not contain the actual data stored in the variable, but they contain a reference to the variable.
A reference type refers to a memory location. When using multiple variables, a reference type can point to a memory location. If the data at a memory location is changed by one variable, the other variables automatically reflect this change in value. The built-in reference types are: object, dynamic, and string.

Object (Object) type

The object type is the ultimate base class for all data types in the C# Common Type System (CTS).
Object is an alias for the System.Object class. So the Object (Object) type can be assigned the value of any other type (value type, reference type, predefined type and user-defined type). However, before assignment, a type conversion is required.
When a value type is converted to an object type, it is called boxing; on the other hand, when an object type is converted to a value type, it is called unboxing.

object obj;
obj = 100; //this is binning
1
2

Dynamic type

Values ​​of any type can be stored in dynamic data type variables, and the type of these variables is checked at runtime.
Syntax for declaring dynamic data types:

dynamic <variable_name> = value;
1
例如:

dyamic d = 20;
1
dynamic type is similar to object type, but object type variable checking happens at compile time, while dynamic type variable checking happens at run time.

String (String) type

String (String) type allows you to assign any string value to the variable. The String (String) type is an alias for the System.String class. It is derived from the Object (Object) type. Values ​​of type String can be assigned in two forms: quotes and @quotes.
For example:

String str = "hello world";
1
An @quoted string:

@"hello world"
1
C#string can be preceded by @ (called "verbatim string") to treat escape characters (\) as ordinary characters, for example:

sting str = @“C:\Windows”;
is equivalent to:
string str = “C:\Windows”;
1
2
3
@The string can be wrapped arbitrarily, and newlines and indentation spaces are included in the length of the string .

string str = @"<script type=""text/javascript"">

";
1
2
3
4User
-defined reference types include: class, interface or delegate.

Pointer types

A variable of pointer type stores another type of memory address. Pointers in C# have the same functionality as pointers in C or C++.
What pointer type syntax:

type* identifier

For example:
char* cptr;
int* iptr;
1
2
3
4
5

type conversion

Type conversion is the conversion of data from one type to another. In C#, type conversion has two forms:

Implicit type conversion: This conversion is C#'s default conversion in a safe manner without causing data loss. For example, converting from a small integer type to a large integer type, and from a derived class to a base class.
Display type conversion: that is, mandatory type conversion. Display conversion requires a cast operator, and the cast causes data loss.
The following example shows an explicit type conversion:

using System;
namespace ExplicitConversion
{ static void Main(string[] args) { double d = 512.6; int a; // cast double to int a = (int)d; Console.WriteLine("a = {0}", a); Console.ReadKey(); } } 1 2 3 4 5 6 7 8 9 10 11 12 13 After the above code is compiled and executed, the result is as follows:























5673
1
C# type conversion method
C# provides the following built-in type conversion methods:

Ordinal method & description
1 ToBoolean If possible, convert the type to a Boolean type
2 ToByte Convert the type to a byte type
3 ToChar If possible, convert the type to a Unicode character type 4
ToDateTime Convert the type (integer or string type) For a date-time structure
5 ToDecimal Converts a floating-point or integer type to a decimal type
6 ToDouble Converts a type to a double-progression floating-point type
7 ToInt16 Converts a type to a 16-bit integer type
8 ToInt32 Converts a type to a 32-bit integer type
9 ToInt64 Convert the type to a 64-bit integer type
10 ToSbyte Convert the type to a signed byte type
11 ToSingle Convert the type to a small floating point type
12 ToString Convert the type to a string type
13 ToType Convert the type to a specified type
14 ToUInt16 Convert the type Convert to 16-bit unsigned integer type
15 ToUInt32 Convert the type to 32-bit unsigned integer type
16 ToUInt64 Convert the type to 64-bit unsigned integer type
The following examples convert the types of different values ​​to string types:

using System;
namespace TypeConversionApplication
{
class StringConversion
{
static void Main(string[] args)
{
int i = 80;
float f = 51.006f;
double d = 123.2563;
bool b = true;
Console.WriteLine(i.ToString());
Console.WriteLine(f.ToString());
Console.WriteLine(d.ToString());
Console.WriteLine(b.ToString());
}
}
}

After the above code is compiled and executed, the result is as follows:

80
51.006
123.2563
True

C# Variables
A variable is nothing more than a stored name for a program operation. In C#, each variable has a specific type, which determines the memory size and layout of the variable. Values ​​within a range can be stored in memory, and a series of operations can be performed on the variable.
The basic types of C# can be roughly divided into the following categories:

Type examples
Integer types sbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating point types float and double
Decimal types decimal
Boolean type true or false
Null type Nullable data type Accepts
values ​​from the user
System The Console class in the namespace provides a function ReadLine() for receiving input from the user and storing it in a variable.
For example:

int num;
num = Convert.ToInt32(Console.ReadLine());
1
2
The function Convert.ToInt32() converts the data entered by the user into an int data type. Because Console.ReadLine() only accepts data in string format.

C# operator

An operator is a symbol that tells the compiler to perform a specific mathematical or logical operation. C#'s built-in operators are categorized as follows:

Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Other operators

arithmetic operator

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

Operator Description Example

  • Add two numbers A + B = 30
  • Subtract the second operand A - B = -10 from the first operand
  • Multiply two numbers A* B = 200
    / Divide two numbers B / A = 2
    % Modulo operator, remainder after division B % A = 0
    ++ Auto-increment operator, increment integer value by 1 A++ Get 11
    – decrement operator, the integer value will be reduced by 1 A – get 9
    The following is a detailed explanation of the increment (++) and decrement operators:

c = a++: first assign a to c, and then perform an auto-increment operation on a.
c = ++a: First perform the self-increment operation on a, and then assign a to c.
c = a–: first assign a to c, and then perform a self-decrement operation on a.
c = --a: first perform a self-decrement operation on a, and then assign a to c.
The above operation is explained by the following example:

using System;
namespace OperatorsApplication
{ class Program { static void Main(string[] args) { int a = 1; int b; //a++ assign value first and then perform self-increment b = a++; Console.WriteLine("a = {0 }", a); Console.WriteLine("b = {0}", b); Console.ReadLine();










        //++a 先进行自增减运算再赋值
        a = 1;//重新进行初始化
        b = ++a;
        Console.WriteLine("a = {0}", a);
        Console.WriteLine("b = {0}", b);
        Console.ReadLine();
        
        //a-- 先进行赋值,再进行自减运算
        a = 1;  //重新进行初始化
        b = a--;
        Console.WriteLine("a = {0}", a);
        Console.WriteLine("b = {0}", b);
        Console.ReadLine();

        //--a 先进行自减运算,再赋值
        a = 1; // 重新进行初始化
        b = --a;
        Console.WriteLine("a = {0}", a);
        Console.WriteLine("b = {0}", b);
        Console.ReadLine();        
        
    }
}

}

Execute the above program, the output is:

a = 2
b = 1
a = 2
b = 2
a = 0
b = 1
a = 0
b = 0

relational operator

All operators supported by C# are listed below. Suppose variable A is 10, and the value of the variable is 20, then:

Operator Description Example
== Checks if the two operands are equal, and if they are equal then the condition is true (A == B) is not true
!= Checks if the two operands are equal, if they are not equal then the condition is true (A ! = B) is true

Check if left operand is greater than right operand, if yes then condition is true (A > B) is not true
< check if left operand is less than right operand, if yes then condition is true (A < B) is true
= check Is the left operand greater than or equal to the right operand, if yes then the condition is true (A >= B) not true <
= Check if the left operand is less than or equal to the right operand, if yes then the condition is true (A <= B) is true

Logical Operators

The following table lists all operators supported by C#. Assuming variable A is Boolean True and variable B is Boolean false, then:

Operator Description Examples
&& is called logical AND operator, if both operands are non-zero, the condition is true (A && B) is false
|| is called logical OR operator, if any of the two operands non-zero, then the condition is true (A
! is called the logical NOT operator, used to reverse the logical state of the operand, if the condition is true then the logical NOT operator will make it false! (A && B) is true

bitwise operator

Bitwise operators operate on bits and perform operations bit by bit. The truth tables for & (bit-and), | (bit-or) and ^ (exclusive-or) are as follows:

pq p&q p|qp^q
0 0 0 0 0 0
1 0 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 (invert each bit)
A >> 2 = 15 (ie A / 22) A Shift two bits to the right
A << 2 = 240 (that is, A * 22) A shifts two bits to the left

assignment operator

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

Operator Description Example
= Simple assignment operator, assigns the value of the right operand to the left operand C = A + B will assign the value of A + B to C +=
Add and assignment operator, adds the value of the right operand The result of the upper left operand is assigned to the left operand C += A, which is equivalent to C = C + A -
= subtraction and assignment operator, and the result of subtracting the right operand from the left operand is assigned to the left operand C -= A It is equivalent to C = C - A
*= multiplication and assignment operator, and assigns the result of multiplying the right operand by the left operand to the left operand. C *= A is equivalent to C = C * A /= division and assignment operator
, Assign the result of dividing the left operand by the right operand to the left operand C /= A, which is equivalent to C = C / A
%= Find the modulo and assignment operator, find the modulus of the two operands and assign the value to the left operand C % = A is equivalent to C = C % A
<<= left shift and assignment operator C <<= 2 is equivalent to C = C << 2

= right shift and assignment operator C >>= 2 is equivalent to C = C >> 2
&= bitwise and and assignment operator C &= 2 is equivalent to C = C & 2
^= bitwise exclusive or and assignment operator C ^= 2 is equivalent to C = C ^ 2
|= bitwise-or and assignment operator C

other operators

The following table lists some other important operators supported by C#, including sizeof, typeof, and ?:.

Operator description instance
sizeof() returns the size of the data type sizeof(int), will return 4
typeof() returns the type of class typeof(StreamReader)
& returns the address of the variable &a; will get the actual address of the variable

  • Variable pointer *a; will point to a variable.
    ?: conditional expression if the condition is true? then X : otherwise Y
    is to determine whether the object is a certain type. If( Ford is Car) // Check if Ford is an object of class Car.
    as Mandatory conversion, no exception will be thrown even if the conversion fails. Object obj = new StringReader("Hello"); StringReader r = obj as StringReader;

Operator precedence in C#

The following table lists the operators in descending order of operator precedence, with operators with higher precedence appearing above the table and operators with lower precedence appearing below the table. In expressions, operators with higher precedence are evaluated first.

Class Operator Associativity
Suffix() [] -> . ++ – Left to Right
Unary + - ! ~ ++ – (type)* & sizeof Right to Left
Multiply and Divide* / % Left to Right
Addition and Subtraction + - Left to Right
Shift << >> Left to Right
Relation < <= > >= Left to Right Right
Equal == != Left to Right
Bitwise AND AND & Left to Right
Bitwise XOR ^ Left to Right
Bitwise OR | Left to Right
Logical AND AND && Left to Right
Logical OR || Left to Right to right
condition?: right to left
comma, left to right

C#judgment

Here is the general form of a typical predicate construct in most programming languages:

Judgment Statements
C# provides the following types of judgment statements.

if statement

An if statement consists of a Boolean expression followed by one or more statements.

The syntax of if:

if (boolean_expression)
{
    
    
    /* 如果布尔表达式为真,则执行该语句*/

The code block inside the if statement will be executed if the Boolean expression is true. If the Boolean expression is false, the first set of code after the if statement ends (after the closing parenthesis) will be executed.
example

using System

namespace ConditionChoose
{
    
    
 
 class Program
 {
    
    
     static void Main(string[] args)
     {
    
    
         /*局部变量的定义*/
         int a = 20;
         /*使用if语句检查布尔条件*/
         if (a > 10)
         {
    
    
             Console.WriteLine("a 大于 10");
         }
         Console.WriteLine("a 的值是{0}", a);
         Console.ReadLine();
     }
 }
}

When the above code is compiled and executed, the result is as follows:

a 大于 10
a 的值是20

if...else statement

An if statement can be followed by an optional else statement, which executes if the Boolean expression is false. Its syntax is as follows:

if(boolean_expression)
{
    
    
    /*如果表达式为真将执行的语句*/
}
else
{
    
    
    /*如果表达式为假将执行的语句*/
}

example

using System

namespace ConditonChoose
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
               int a = 20;
                /*检查布尔条件*/
                if (a > 30)
                {
    
    
                        Console.WriteLine("a 大于 30")
                }
                else
                {
    
    
                    Console.WriteLine("a  小于 30")
                }
                Console.WriteLine("a 的值是{0}", a);
                Console.ReadLine();
          }
    }
}

When the above code is compiled and executed, the result is as follows:

a  小于 30
a的值是20

if...else if...else statement

An if statement can be followed by an optional else if…else statement, which can be used to test multiple conditions.

When using the if...else if...else statement, the following points should be noted:

An if can be followed by zero or one else, it must be after any else if.
An if can be followed by zero or more else ifs, they must be before the else.
Once an else if matches successfully, other else if or else will not be tested.
The syntax is as follows:

if(boolean_expression 1)
{
    
    
   /* 当布尔表达式 1 为真时执行 */
}
else if( boolean_expression 2)
{
    
    
   /* 当布尔表达式 2 为真时执行 */
}
else if( boolean_expression 3)
{
    
    
   /* 当布尔表达式 3 为真时执行 */
}
else 
{
    
    
   /* 当上面条件都不为真时执行 */
}

example

using System;

namespace DecisionMaking
{
    
    
   
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    

            /* 局部变量定义 */
            int a = 100;

            /* 检查布尔条件 */
            if (a == 10)
            {
    
    
                /* 如果 if 条件为真,则输出下面的语句 */
                Console.WriteLine("a 的值是 10");
            }
            else if (a == 20)
            {
    
    
                /* 如果 else if 条件为真,则输出下面的语句 */
                Console.WriteLine("a 的值是 20");
            }
            else if (a == 30)
            {
    
    
                /* 如果 else if 条件为真,则输出下面的语句 */
                Console.WriteLine("a 的值是 30");
            }
            else
            {
    
    
                /* 如果上面条件都不为真,则输出下面的语句 */
                Console.WriteLine("没有匹配的值");
            }
            Console.WriteLine("a 的准确值是 {0}", a);
            Console.ReadLine();
        }
    }
}

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

no matching values

a 的准确值是 100

Nested if statements

In C#, nested if-else statements are legal, which means you can use one if or else if statement inside another if or else if statement.

grammar

if( boolean_expression 1)
{
    
    
   /* 当布尔表达式 1 为真时执行 */
   if(boolean_expression 2)
   {
    
    
      /* 当布尔表达式 2 为真时执行 */
   }
}

You can nest else if…else in a similar way to nesting if statements.
example

using System;

namespace DecisionMaking
{
    
    
   
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    

            //* 局部变量定义 */
            int a = 100;
            int b = 200;

            /* 检查布尔条件 */
            if (a == 100)
            {
    
    
                /* 如果条件为真,则检查下面的条件 */
                if (b == 200)
                {
    
    
                    /* 如果条件为真,则输出下面的语句 */
                    Console.WriteLine("a 的值是 100,且 b 的值是 200");
                }
            }
            Console.WriteLine("a 的准确值是 {0}", a);
            Console.WriteLine("b 的准确值是 {0}", b);
            Console.ReadLine();
        }
    }
}

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

a 的值是 100,且 b 的值是 200
a 的准确值是 100
b 的准确值是 200

switch statement

A switch statement allows testing when a variable is equal to multiple values. Each value is called a case, and the variable being tested is checked for each switch case.
grammar

switch(expression){
    
    
    case constant-expression  :
       statement(s);
       break; 
    case constant-expression  :
       statement(s);
       break; 
  
    /* 您可以有任意数量的 case 语句 */
    default : /* 可选的 */
       statement(s);
       break; 
}

A switch statement must obey the following rules:

The expression in the switch statement must be an integral or enumeration type, or a class type where the class has a single conversion function to convert it to the integral or enumeration type.
There can be any number of case statements in a switch. Each case is followed by a value to compare and a colon.
The constant-expression of the case must have the same data type as the variable in the switch and must be a constant.
When the variable being tested is equal to the constant in the case, the statements following the case will be executed until a break statement is encountered.
When a break statement is encountered, the switch terminates, and the control flow will jump to the next line after the switch statement.
Not every case needs to contain a break. If the case statement is empty, it does not need to contain a break, and the control flow will continue with subsequent cases until a break is encountered.
C# does not allow execution to continue from one case section to the next. If the case statement has already been executed, it must contain a break or other jump statement.
A switch statement can have an optional default statement at the end of the switch. The default statement is used to execute a task when none of the above cases are true. default also needs to contain a break statement, which is a good habit.
C# does not support explicit penetration from one case label to another. If you want C# to support explicit penetration from one case label to another, you can use goto a switch-case or goto default.
example

using System;

namespace MyApplication
{
    
    
  class Program
  {
    
    
    static void Main(string[] args)
    {
    
    
      int day = 4;
      switch (day)
      {
    
    
        case 1:
          Console.WriteLine("Monday");
          break;
        case 2:
          Console.WriteLine("Tuesday");
          break;
        case 3:
          Console.WriteLine("Wednesday");
          break;
        case 4:
          Console.WriteLine("Thursday");
          break;
        case 5:
          Console.WriteLine("Friday");
          break;
        case 6:
          Console.WriteLine("Saturday");
          break;
        case 7:
          Console.WriteLine("Sunday");
          break;
      }    
    }
  }
}

The execution results vary according to the date of the day. The results of my execution for this day are:

Thursday

The following example judges the grades of students, including the default statement:

using System;

namespace DecisionMaking
{
    
    
   
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            /* 局部变量定义 */
            char grade = 'B';

            switch (grade)
            {
    
    
                case 'A':
                    Console.WriteLine("很棒!");
                    break;
                case 'B':
                case 'C':
                    Console.WriteLine("做得好");
                    break;
                case 'D':
                    Console.WriteLine("您通过了");
                    break;
                case 'F':
                    Console.WriteLine("最好再试一下");
                    break;
                default:
                    Console.WriteLine("无效的成绩");
                    break;
            }
            Console.WriteLine("您的成绩是 {0}", grade);
            Console.ReadLine();
        }
    }
}

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

做得好
您的成绩是 B

Nested switch statements

You can use a switch as part of an outer switch statement sequence, that is, you can use a switch statement inside another switch statement. Even if the case constants of the inner and outer switch contain common values, there is no contradiction.
grammar

switch(ch1)
{
    
    
   case 'A':
      printf("这个 A 是外部 switch 的一部分" );
      switch(ch2)
      {
    
    
         case 'A':
            printf("这个 A 是内部 switch 的一部分" );
            break;
         case 'B': /* 内部 B case 代码 */
      }
      break;
   case 'B': /* 外部 B case 代码 */
}

example

using System;

namespace DecisionMaking
{
    
    
   
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            int a = 100;
            int b = 200;

            switch (a)
            {
    
    
                case 100:
                    Console.WriteLine("这是外部 switch 的一部分");
                    switch (b)
                    {
    
    
                        case 200:
                        Console.WriteLine("这是内部 switch 的一部分");
                        break;
                    }
                    break;
            }
            Console.WriteLine("a 的准确值是 {0}", a);
            Console.WriteLine("b 的准确值是 {0}", b);
            Console.ReadLine();
        }
    }
}

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

这是外部 switch 的一部分
这是内部 switch 的一部分
a 的准确值是 100
b 的准确值是 200

? : operator

We have explained the conditional operator ? : in previous chapters, which can be used instead of if…else statement. Its general form is as follows:

Exp1 ? Exp2 : Exp3;
1
where Exp1, Exp2 and Exp3 are expressions. Note the use and placement of colons.
? The value of the expression is determined by Exp1. If Exp1 is true, the value of Exp2 is evaluated and the result is the value of the entire ? expression. If Exp1 is false, the value of Exp3 is evaluated and the result is the value of the entire ? expression.

C# Loop
Sometimes, it may be necessary to execute the same block of code multiple times. In general, statements are executed sequentially: the first statement in a function is executed first, followed by the second statement, and so on.

Loop type
while loop
As long as the given condition is true, the while loop statement in C# will repeatedly execute a target statement
Syntax

while(condition)
{
    
    
   statement(s);
}

Here, statement(s) can be a single statement or a block of several statements. condition can be any expression that is true for any non-zero value. Execute the loop while the condition is true.
When the condition is false, program flow continues with the next statement immediately following the loop.

example

using System;

namespace Loops
{
    
    
   
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            /* 局部变量定义 */
            int a = 10;

            /* while 循环执行 */
            while (a < 20)
            {
    
    
                Console.WriteLine("a 的值: {0}", a);
                a++;
            }
            Console.ReadLine();
        }
    }
}

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

a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
a 的值: 16
a 的值: 17
a 的值: 18
a 的值: 19

for/foreach loop

A for loop is a repeating control structure that allows you to write a loop that executes a specific number of times.
grammar

for ( init; condition; increment )
{
    
    
   statement(s);
}

The following is the control flow of the for loop:

init will be executed first, and only once. This step allows you to declare and initialize any loop control variables. You can also not write any statement here, as long as a semicolon appears.

Next, the condition will be judged. If true, the loop body is executed. If false, the loop body is not executed and control flow jumps to the next statement immediately following the for loop.

After executing the body of the for loop, the flow of control jumps back to the increment statement above. This statement allows you to update loop control variables. This statement can be left blank as long as a semicolon appears after the condition.

The condition is evaluated again. If it is true, the loop is executed, and the process is repeated (the loop body, then increment the step value, and then re-evaluate the condition). The for loop terminates when the condition becomes false.

example

using System;

namespace Loops
{
    
    
   
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            /* for 循环执行 */
            for (int a = 10; a < 20; a = a + 1)
            {
    
    
                Console.WriteLine("a 的值: {0}", a);
            }
            Console.ReadLine();
        }
    }
}

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

a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
a 的值: 16
a 的值: 17
a 的值: 18
a 的值: 19

C# also supports the foreach loop, using foreach to iterate over an array or a collection object.

The following example has three parts:

Output the elements in the integer array through the foreach loop.
Output the elements in the integer array through a for loop.
The foreach loop sets the counter for the elements of the array.

class ForEachTest
{
    
    
    static void Main(string[] args)
    {
    
    
        int[] fibarray = new int[] {
    
     0, 1, 1, 2, 3, 5, 8, 13 };
        foreach (int element in fibarray)
        {
    
    
            System.Console.WriteLine(element);
        }
        System.Console.WriteLine();


        // 类似 foreach 循环
        for (int i = 0; i < fibarray.Length; i++)
        {
    
    
            System.Console.WriteLine(fibarray[i]);
        }
        System.Console.WriteLine();


        // 设置集合中元素的计算器
        int count = 0;
        foreach (int element in fibarray)
        {
    
    
            count += 1;
            System.Console.WriteLine("Element #{0}: {1}", count, element);
        }
        System.Console.WriteLine("Number of elements in the array: {0}", count);
    }
}

References:
Runboob.com

Guess you like

Origin blog.csdn.net/weixin_45428910/article/details/131504078