简单复习一下 C# 基础语法(第一期)。
基础语法
注释
输入输出
1 2 3 4 5 6
| Console.Write("输出"); Console.WriteLine("输出并换行");
Console.ReadLine();
|
关键字
在 C# 中被规定了用途的单词,声明变量时,变量名不可与关键字冲突。
1 2 3 4
| namespace using class
|
数据类型
1 2 3 4 5 6
| char gender = '男'; string name = "柯南"; int age = 3; float money = 0.1f; double salary = 0.1; bool hasMoney = false;
|
常量
声明并赋值,不可修改。
变量
声明时可以赋值,如果没有赋值则会有相应类型的默认值。
1 2
| double money = 0.1; int num;
|
类型转换
低精度类型会自动转换成高精度类型
高精度类型需要强制转换成低精度类型,并且会丢失部分精度。
1 2
| double i = 2; int j = (int)3.1;
|
枚举
枚举值是从 0 递增的整数。
使用枚举可以限制变量只能从有限的选项中取值,避免随意取值。
1 2 3 4 5 6 7 8 9 10
| enum Gender { Boy, Girl }
Gender.Boy Gender.Girl
|
数组
一维数组
1 2 3 4 5 6 7 8
| string[] students = new string[3];
string[] students1 = new string[] { "A", "B", "C" }; string[] students2 = { "A", "B", "C" }; string[] students3 = new string[3] { "A", "B", "C" };
Console.WriteLine(students1[0]);
|
二维数组
1 2 3 4 5 6
| int[,] scores = new int[3, 2] { { 11, 23 }, { 25, 44 }, { 76, 13 } };
Console.WriteLine(scores[0, 0]); Console.WriteLine(scores[1, 1]);
|
条件分支
if 语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| bool hasMoney = false; bool hasEnergy = false;
if (hasMoney) { Console.WriteLine("买买买"); } else if (hasEnergy) { Console.WriteLine("冲冲冲"); } else { Console.WriteLine("发呆"); }
|
switch 语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| string name = "小樱";
switch (name) { case "小樱": Console.WriteLine("魔法杖"); break; case "知世": Console.WriteLine("摄像机"); break; default: Console.WriteLine("未知"); break; }
|
循环
for 循环
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| for (int i = 0; i < 5; i++) { if (i == 3) { continue; } Console.WriteLine(i); }
|
foreach 循环
1 2 3 4 5 6 7 8 9 10 11
| int[] num = {1, 2, 3};
foreach (int x in num) { Console.WriteLine(x); break; }
|
while 循环
1 2 3 4 5 6 7 8 9 10 11 12 13
| int i = 0;
while (i < 3) { Console.WriteLine(i); i++; }
|
do while 循环
1 2 3 4 5 6 7 8 9 10 11 12
| int i = 1;
do { Console.WriteLine(i); i++; } while (i < 0);
|