Summary of introductory knowledge of C# (based on C language)

Preface

This article is an introduction to C#. It is a summary based on a certain knowledge of C language or C++. Therefore, many basic knowledge of C language will be omitted. However, some knowledge unique to C# or relatively rare or important in C language will also be summarized. In the blog post.

Table of contents

Preface

1. Input and output

2. Variables

1. Fold the code

2. Declare variables

a.Signed integer variable

b. Unsigned integer variable

c.Floating point number

d.Special type

3. Constants

4. Escape characters

5. Type conversion

1. Implicit conversion

a. Conversion between same types

b. Conversion between different large types

2.Explicit conversion

a. Parentheses forced transfer

b.Parse method forcefully converts the string type into the corresponding type

c.Convert method

d. Convert other types to string

7. Arithmetic operators

8. String splicing

1.string can be concatenated using +

2. String splicing method 2

3.Console printing splicing

9. Conditional operator

1. Between different numerical types

2. Special type char string bool

10. Logical operators

1. Attention

2. Logical operator short-circuit rules

11. Bit operators

1. Bitwise AND operation &

2. Bitwise OR operation| 

3.XOR operation ^

4. Bit inversion~ (Just understand it)

5. Move left<< and move right>> (just understand it)

12. Ternary operator

13. if statement

14. switch statement

15. while statement

16. do while statement

17. for loop


1. Input and output

  • Console.WriteLine() prints a line of information and automatically wraps the line
  • Console.Write() will not automatically wrap the line after printing the information.
  • Console.ReadLine() user input, click Enter to end
  • Console.ReadKey() will end when the user presses the keyboard any time

2. Variables

1. Fold the code

Function: Folds the code wrapped in the middle to avoid messy code editing.

#region MyRegion

...

#endregion

2. Declare variables

Formula: variable type variable name = initial value;

There are 14 types of variables:

a.Signed integer variable

Can store positive and negative numbers and 0. The approximate range is given below (an error will be reported if the value exceeds the range when assigning)

  • sbyte -128~-127
  • int -2.1 billion~2.1 billion
  • short -32768~32767
  • long -9 trillion ~ 9 trillion

Sample code

sbyte a = 1;

Console.WriteLine("存储的数:"+a); //输出之间的连接用+

b. Unsigned integer variable

Can store a certain range of 0 and positive numbers

  • byte 0~255
  • uint 0~4.2 billion
  • ushort 0~65535
  • ulong 0~18 trillion

c.Floating point number

  • float stores 7 or 8 significant digits, depending on compiler rounding starting with non-zero digits from left to right.
  • Double stores 15~17 significant digits. The default double type for declaring decimals in C# is
  • decimal stores 27~28 bits
float f = 0.1234f; //后面要加f 大小写均可

double d = 0.12456434;

decimal de = 0.124543534234t254m; //后面要加m 大小写均可

d.Special type

  • bool variable value is true or false, indicating true or false data type
  • char stores a single character and encloses the value to be assigned in single quotes.
  • string stores the string in double quotes to enclose the value to be assigned.
string s1="hello", s2="world", s3="good"; //多个变量同时声明

3. Constants

Declaration of constants (characteristics: must be initialized and cannot be modified)

const variable type variable name = initial value;

const int i = 10;

4. Escape characters

Formula: \character

Commonly used escape characters are as follows:

apostrophe

\'

Double quotes

\"

newline

\n

slash

\\

Tab tabulation

\t

backspace

\b

5. Type conversion

1. Implicit conversion

Rules: (automatic conversion between different types) large range to small range

a. Conversion between same types

long a = 1;
int  b = 2;
a = b;//int隐式转换为long
b = a;//这句是不对的!小范围不能转大范围

For floating point numbers, it should be noted that the decimal type cannot use implicit conversion to store double and float, but float can be converted to double. There is no implicit conversion between special types bool, char and string.

b. Conversion between different large types

! Signed variables cannot be implicitly converted to unsigned variables

Error code example:

ushort us2 = 1;
sbyte sb2 = 1;
us2 = sb2;//错误代码!不能转换

! Unsigned variables can be converted to signed variables, but the prerequisite is that the scope covered by the signed variable must include the unsigned type.

int i2 = 1;
uint ui2 = 1;
byte b2 = 1;
i2 = ui2;// 错误!无法覆盖无符号数的全部范围
i2 = b2;// 正确代码
  • Floating point numbers can load any type of integer, whether unsigned or signed (decimal cannot implicitly store float and double but can implicitly store integers)
  • Integers cannot implicitly store floating point numbers
  • The bool type cannot be implicitly converted to other types.
  • Char cannot implicitly store variables of other types, but the char type can be converted to the int type, and the int type can be implicitly converted to other types.

2.Explicit conversion

Requires manual handling of casts

Formula: variable type variable name = (variable type) variable

a. Parentheses forced transfer

(1) Between the same categories (unsigned integers, signed integers, floating point numbers), forced conversion of brackets may cause range problems and cause exceptions.

short s = 1;
int i = 1;
s = (short)i;

(2) Between different types

  • Forced conversion between signed and unsigned can also occur, but range issues may occur.
  • Converting floating point numbers to integers is mainly a matter of accuracy
  • Bool and string do not support forced transfer.

b.Parse method forcefully converts the string type into the corresponding type

Variable type.Parse("string") The string must be able to be converted into the corresponding type, otherwise an error will be reported 

int i4 = int.Parse("123");
float f3 = float.Parse("1.232");
bool b = bool.Parse("true");
int i4 = int.Parse("123.45");//错误语句,会报错!
short s4 = short.parse("300000");//错误语句,超出范围,会报错!

c.Convert method

More accurate conversion between types

Convert.To target type (variable or constant) Converting a string to the corresponding type must be legal and compliant

int a = Convert.ToInt32("12");
int a = Convert.ToInt32(12.2f);//正确语句 且Convert精度更高,可以四舍五入
int a = Convert.ToInt32(ture);//正确语句 true转为1,false转为0
int a = Convert.ToInt32('a');//正确语句 char转为对应ASCII码
int a = Convert.ToInt32("12.2");//错误,不合法转换
  • Convert other methods ToSByte(), ToInt16(), ToInt64() //16 represents short, 32 represents int, 64 represents long
  • Similarly, if it is an unsigned type ToByte(), ToUInt16/32/64()
  • Floating point numbers: ToSingle(), ToDouble(), ToDecimal()
  • Special types: ToBoolean(), ToChar(), ToString()

d. Convert other types to string

The function is to splice and print

Variable.ToString(); //Any type can be used

string str = 1.ToString();
Console.WriteLine("123"+1+true);//这句话是正确的,后面两个会默认调用ToString方法

6. Exception catching

Use exception capture to prevent the program from getting stuck when the code reports an error.

Basic syntax:

try
{
    //希望进行异常捕获的代码块
    //如果出错执行catch中的 
}
catch
{
    //catch(Excepetion e) 具体报错跟踪 通过e得到具体错误信息
}
//可选部分
finally
{
    //不管有没有错都会执行
}

7. Arithmetic operators

No different from C language

8. String splicing

1.string can be concatenated using +

string str = "123";
str = str + "456";//正确
str = str + 1;//正确,默认调用1.ToString();
str += "1" + 4 + true;//正确,复合运算和ToString()都起作用

2. String splicing method 2

string.Format("Content to be spliced", content 1, content 2);

The content that you want to splice is replaced with {number} with placeholders: 0~n in order.

string str2;
str2 = string.Format("我是{0},我今年{1}岁,我想要{2}","Daniel",18,"study");

3.Console printing splicing

If the following content is more than the placeholder, no error will be reported, but if it is less than the placeholder, an error will be reported.

Console.WriteLine("A{0},B{1},C{2}",1,ture,false);

9. Conditional operator

Notation is the same as C language

1. Between different numerical types

Rule: Feel free to do conditional operator comparisons

int i = 5;
float f = 1.2f
short s = 2;
byte by = 20;
uint ui = 222;

// 以下语句都成立 只要是数值都可以进行比较
result = i > f;
result = f < d;
result = f > by;

2. Special type char string bool

Rule: == and != can only be compared between the same type

Since char is a special integer type, it can be compared with its own type, compared with numeric types, and compared with character types.

char c = 'a';
result = c > 123;
result = c > 'B';

10. Logical operators

Logical AND: && Logical OR: || Logical NOT: !

Notations and rules are the same as in C language

1. Attention

Among logical operators, logical NOT (!) has the highest priority, and logical AND (&&) has higher priority than logical OR (||).

Logical operators have lower precedence than conditional operators and arithmetic operators

2. Logical operator short-circuit rules

As long as the left side of logical AND or logical OR satisfies the condition, the right side does not need to be executed again.

For example, if logical AND is false, then the expression on the left is false, and the right side does not need to be executed again.

11. Bit operators

Rule: Concatenate two values ​​to perform bit calculations and convert the values ​​to binary

1. Bitwise AND operation &

Rule: If there is 0, then 0

int a = 1; // 002
int b = 5; // 101
int c = a & b;
// 001 & 101 =  001 所以c也就是1

2. Bitwise OR operation| 

There is 1 or 1

1|0=1

3.XOR operation ^

Rule: Same as 0, different as 1

  • 1 ^ 1 = 1
  • 0 ^ 0 = 1

4. Bit inversion~ (Just understand it)

Write in front of the value to convert the value to binary

0 changes to 1, 1 changes to 0, involving complement code 

5. Move left<< and move right>> (just understand it)

Let the binary system of a number be shifted left and right

Shift a few bits to the left and add a few 0s to the right.

Move a few numbers to the right and remove a few numbers to the right.

12. Ternary operator

The principle is equivalent to C language

13. if statement

The principle is equivalent to C language

14. switch statement

The principle is equivalent to C language

15. while statement

The principle is equivalent to C language

16. do while statement

The principle is equivalent to C language

17. for loop

The principle is equivalent to C language

The next article is a summary of the basic knowledge of C#, welcome to continue reading

Summary of basic knowledge of C# (based on C language)_Daniel's blog-CSDN blog

Guess you like

Origin blog.csdn.net/danielxinhj/article/details/130401403