新手学c#常用到的语法记录
发布人:shili8
发布时间:2025-01-24 09:03
阅读次数:0
**C# 新手必备语法记录**
作为一名新手程序员,学习 C# 是一个很好的开始。下面是一些常用的 C#语法记录,包括变量、数据类型、运算符、控制结构、函数等。
### 变量和数据类型在 C# 中,变量是用来存储值的容器。每个变量都有一个特定的数据类型。
#### 基本数据类型* **整数**: `int` 是32 位有符号整数。
csharp// 声明一个整数变量int age =25; Console.WriteLine(age); // 输出:25
* **浮点数**: `float` 和 `double` 是32 位和64 位浮点数。
csharp// 声明一个浮点数变量float pi =3.14f; Console.WriteLine(pi); // 输出:3.14double d =3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679; Console.WriteLine(d); // 输出:3.141592653589793
* **布尔值**: `bool` 是一个布尔值,表示真或假。
csharp// 声明一个布尔变量bool isAdmin = true; Console.WriteLine(isAdmin); // 输出: True
* **字符**: `char` 是一个单个字符。
csharp// 声明一个字符变量char c = 'A'; Console.WriteLine(c); // 输出: A
#### 复合数据类型* **数组**: `int[]`、`float[]` 等是数组的例子。
csharp// 声明一个整数数组int[] scores = new int[5]; scores[0] =90; scores[1] =80; scores[2] =70; scores[3] =60; scores[4] =50; Console.WriteLine(scores[0]); // 输出:90
* **集合**: `List
csharp// 声明一个整数列表List<int> scores = new List<int>(); scores.Add(90); scores.Add(80); scores.Add(70); Console.WriteLine(scores[0]); // 输出:90
#### 类型转换在 C# 中,可以使用 `int.Parse()`、`float.Parse()` 等方法将字符串转换为基本数据类型。
csharp// 将字符串转换为整数string str = "25"; int age = int.Parse(str); Console.WriteLine(age); // 输出:25
### 运算符C# 支持各种运算符,包括算术运算符、比较运算符、逻辑运算符等。
#### 算术运算符* **加法**: `+`
csharp// 加法运算int a =5; int b =3; Console.WriteLine(a + b); // 输出:8
* **减法**: `-`
csharp// 减法运算int a =5; int b =3; Console.WriteLine(a - b); // 输出:2
* **乘法**: `*`
csharp// 乘法运算int a =5; int b =3; Console.WriteLine(a * b); // 输出:15
* **除法**: `/`
csharp//除法运算int a =10; int b =2; Console.WriteLine(a / b); // 输出:5
#### 比较运算符* **等于**: `==`
csharp// 等于运算int a =5; int b =3; Console.WriteLine(a == b); // 输出: False
* **不等于**: `!=`
csharp// 不等于运算int a =5; int b =3; Console.WriteLine(a != b); // 输出: True
#### 逻辑运算符* **与**: `&&`
csharp// 与运算bool isAdmin = true; bool isModerator = false; Console.WriteLine(isAdmin && isModerator); // 输出: False
* **或**: `||`
csharp// 或运算bool isAdmin = true; bool isModerator = false; Console.WriteLine(isAdmin || isModerator); // 输出: True
### 控制结构C# 支持各种控制结构,包括条件语句、循环语句等。
#### 条件语句* **if**
csharp// if语句int age =25; if (age >=18) { Console.WriteLine("You are an adult."); }
* **else**
csharp// else语句int age =15; if (age >=18) { Console.WriteLine("You are an adult."); } else{ Console.WriteLine("You are a minor."); }
#### 循环语句* **for**
csharp// for语句for (int i =0; i < 5; i++) { Console.WriteLine(i); }
* **while**
csharp// while语句int i =0; while (i < 5) { Console.WriteLine(i); i++; }
### 函数C# 支持函数的定义和调用。
#### 函数定义
csharp// 函数定义public static void PrintHelloWorld() { Console.WriteLine("Hello, World!"); } PrintHelloWorld();
#### 函数参数
csharp// 函数参数public static int Add(int a, int b) { return a + b; } int result = Add(5,3); Console.WriteLine(result); // 输出:8
### 总结以上是 C# 新手必备语法记录的一些内容。这些内容涵盖了变量、数据类型、运算符、控制结构和函数等方面。通过学习这些内容,新手程序员可以快速上手 C# 并开始编写自己的程序。