(C#) Introduction to Simplified C# (2)

Recently, I have been working on some projects that need to be developed using C#, and I haven't touched it for a long time. So I decided to quickly go through the basic content of the language. For ease of reference, the most condensed parts are selected and organized on this blog.

【illustrate】

  1. The goal of this series is to sort out less than ten blogs ( portals ), each of which contains about 10 very short Sections, suitable for getting started quickly. Currently updated to: Simplified C# Getting Started (4)
  2. this seriesNot suitable for complete programming beginners (not exposed to any computer language), this type of readers is recommended to carefully study the video resources in [References]

[References]
1. Station b: [01_C# entry to master] Novices strongly recommend: C# development course, a complete set of courses

#1 Exception Handlingtry-catch

Similar to Python'stry-except

try
{
    
    
	// 可能出现异常的代码块
}
catch
{
    
    
	// 出现异常后需要执行的代码块
}

Used properly try-catch, some effects can be achieved that cannot be achieved with if elsestatements , such as:

int n = 0;
Console.WriteLine("请输入一个数字");
try
{
    
    
	n = Convert.ToInt32(Console.ReadLine());
}
catch
{
    
    
	Console.WriteLine("请不要输入其他字符!");
}

#2 Check the running time

For two different algorithms, the pros and cons can be judged by comparing their running times. Example:

using System.Diagnostics; // 需要现在开头引用一个命名空间

Stopwatch sw = new Stopwatch();
sw.Start();
// 算法
sw.Stop();
Console.WriteLine(sw.Elapsed);

#3 Selection and looping: if & for

Use Tab + Tabshortcut keys to quickly generate structure formats, for example, enter and press fordirectly twice Tab, the effect:

for (int i = 0; i < length; i++)
{
    
    

}

Most of the rest of the structs apply to this shortcut

3.1 if else

if (判断条件 1)
{
    
    
	// 代码块
}
else if (判断条件 2)
{
    
    
	// 代码块
}
else
{
    
    
	// 代码块
}

3.2 switch case

switch (变量或表达式的值)
{
    
    
	case1: // 代码
		break;
	case2: // 代码
		break;
	default: // 代码
		break;
}

3.3 while

while (循环条件)
{
    
    
	// 代码块
}

Use breakto jump out of the current loop
Use continueto skip this loop and return to the loop condition

3.4 do while

while loop: first judge and then execute
do while loop: first execute and then judge

do
{
    
    
	// 代码块
}while(循环条件)

3.5 for

for (int i = 0; i < length; i++)
{
    
    
	// 代码块
}

3.6 for each

foreach (var item in collection)
{
    
    
	// 代码块
}

varFor details, please refer to Introduction to C# (1) Section #5.2, which can be replaced with other data types,
collectionincluding arrays (int[]…) and collections (ArrayList, HashTable)

数组The introduction about in the above code is located in Section #11 of this blog, and 集合this concept can be ignored first, and its content will be introduced in detail in Section #7, #8 of Simplified C# Introduction (4)

#4 Breakpoints and Debugging

Add a breakpoint first, and then press F5to debug Step by
F11step debugging (single-step debugging) debug
F10process by process. Compared to statement-by-statement debugging, procedure-by-procedure debugging does not jump into specific functions. For example, in the figure below , instead F10of jumping into GetMaxthe function , it F11will execute each line of code statement by statement.
insert image description here

#5 Ternary expressions

grammar:

变量 = 表达式1 ? 表达式2 : 表达式3

表达式1True to execute 表达式2, False to execute 表达式3, for example:

int max = n1 > n2 ? n1 : n2;

#6 Generate random numbers

This piece is suddenly inserted in the middle of P61 of [References] (1). Personally, I feel that its relationship with the context is a bit disconnected, so I only make a brief summary.

Random r = new Random();    // 创建能够生成随机数的对象
int rndInt = r.Next(1, 10); // 调用该对象的方法,产生一个 1-9 之间的随机数  

#7 Constants

const 常量类型 常量名 = 常量值;
const double pi = 3.14;

In contrast to variables, constants cannot be modified (reassigned)

#8 Enumerationenum

The enumeration type is a special class, which is at the same level as the class, so it is written directly in the namespace, and the definition is:

public enum Gender
{
    
    
	man,
	woman
}

With Genderthis class, in the Main function later, we can create class objects, for example:

Gender gender = Gender.man;

The more specific usage is as follows: the
insert image description here
enumeration type is compatible with the inttype (can be converted to each other), and the just defined Genderclass :

Gender gender = Gender.woman;
int n = (int)gender;

>>> 
"1"
int n = 0;
Gender gender = (Gender)n;

>>> 
"man"

To make things more complicated, variables in enumeration types can also be assigned values. After an assignment, the variable is converted intto a value equal to the assignment. And the intvalues will also change, as shown in the figure below: The

enumeration type stringis incompatible with , so it is more troublesome to convert each other (especially stringto enumeration). Using the above Animalclass as an example:

// 枚举转 string
string str = Animal.dog.ToString();

>>>
"dog"
// string 转枚举
string str = "dog";
Animal animal = (Animal)Enum.Parse(tyepof(Animal), str);

>>>
"dog"

#9 Structurestruct

Declare multiple variables of different types at once

public struct Person
{
    
    
	public string _name,
	public string _gender,
	public int _age,

	string _nickname
}

publickeyword makes its modifiedfieldCan be accessed and modified from the outside, such as the _name field. Fields not publicdecorated with are defaulted to privateand cannot be modified externally, such as _nickname.

Note : We refer to the "variables" in the structure as fields. Unlike the uniqueness of variables, multiple fields with the same name can exist at the same time, for example, different people can have the same _name field. thereforeIn order to reflect this difference, it is generally customary to add an underscore before the field

Example: enuminstruct

public struct Person
{
    
    
	public string _name,
	public Gender _gender,
	public int _age,

	string _nickname
}

public enum Gender
{
    
    
	man,
	woman
}

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        Person p1;
        p1._name = "小红";
        p1._gender = Gender.woman;
        p1-_age = 99;
    }
}

#10 Array list

Store multiple variables of the same type at once

数组类型[] 数组名 = new 数组类型[(数组长度)] // ()意味着可以省略

array declaration

Example (1):

int[] nums = new int[10]; // 声明一个数组,此时默认数组内 10 个元素均为 0
nums[0] = 1;              // 修改第 0 个元素为 1

Example (2):

int[] nums1 = {
    
    123}int[] nums2 = new int[3] {
    
    1, 2, 3};

array properties

nums.Length >>> 10 // 长度

Unlike variables, external functionsYou can directly modify the incoming array to change the value of the array outside the function. For example, in the following code, the Changefunction changes Mainthe array in the function nums, but does not change the variable n:

static void Main(string[] args)
{
    
    
    int n = 0;
    int[] nums = {
    
     0 };
    Program.Change(n, nums);

    Console.WriteLine(n);
    Console.WriteLine(nums[0]);
    Console.ReadKey();
}

static void Change(int n, int[] nums)
{
    
    
    n += 1;
    nums[0] += 1; 
}

>>>
"0
1"

#11 Bubble Sort

Since the default readers of this blog are not completely ignorant of any other computer languages, the principle of bubble sort will not be repeated here. Directly give the implementation of C# bubble sort (from small to large):

int[] nums = {
    
     3, 4, 7, 1, 6, 6, 8 };
for (int i = 0; i < nums.Length; i++)
{
    
    
    for (int j = 0; j < nums.Length-1-i; j++)
    {
    
    
        if (nums[j] > nums[j+1])
        {
    
    
            int temp = nums[j+1];
            nums[j+1] = nums[j];
            nums[j] = temp;
        }
    }
}
for (int i = 0; i < nums.Length; i++) {
    
     Console.Write(nums[i]); }
Console.ReadKey();

>>>
"1346678"

Of course, there are built-in methods in C# that can help us quickly sort the array in ascending or descending order:

Array.Sort(nums);    // 升序
Array.Reverse(nums); // 降序

Guess you like

Origin blog.csdn.net/weixin_43728138/article/details/115793759