C# - 速查表
C# 现代速查表
Section titled “C# 现代速查表”本速查表提供了对 C# 基本和现代概念的快速参考。C# 是一种多功能、跨平台的语言,由 .NET 生态系统提供支持,用于构建 Web API、云服务、桌面、移动和游戏应用程序。本指南将帮助您快速掌握开发、面试和考试的关键语法和功能。
1. 基本程序结构(现代 .NET)
Section titled “1. 基本程序结构(现代 .NET)”现代 C#(.NET 6+)使用顶级语句来简化控制台应用程序的代码。
// 对于简单的程序,不需要 'using System;'、'namespace'、'class' 或 'Main' 方法。Console.WriteLine("Hello, Modern C#!");// 这是单行注释。
/*这是多行注释。*/
/// <summary>/// 这是用于生成文档的 XML 文档注释。/// </summary>3. 数据类型
Section titled “3. 数据类型”值类型(直接存储数据)
Section titled “值类型(直接存储数据)”- 整数:
int、long、short、byte(以及无符号的uint、ulong等) - 浮点数:
double(默认)、float、decimal(用于高精度财务计算) - 布尔:
bool(true或false) - 字符:
char(单个 Unicode 字符) - 结构体:
struct(用户定义的值类型) - 枚举:
enum(一组命名常量)
引用类型(存储数据的引用/地址)
Section titled “引用类型(存储数据的引用/地址)”- 字符串:
string(不可变字符序列) - 数组:
int[]、string[]等 - 类:
class(对象的蓝图) - 记录类型:
record(C# 9 中新增的不可变类或结构体) - 接口:
interface(类的契约) - 委托:
delegate(表示方法签名的一种类型)
4. 变量和常量
Section titled “4. 变量和常量”// 变量声明string name = "Alice";int age = 30;
// 'var' 从值中推断类型var message = "Hello, World!"; // 编译器知道 'message' 是一个字符串
// 常量声明(值必须在编译时已知)const double Pi = 3.14159;5. 条件语句
Section titled “5. 条件语句”int temperature = 25;
if (temperature < 0) { Console.WriteLine("结冰!");} else if (temperature > 30) { Console.WriteLine("炎热!");} else { Console.WriteLine("温度适中。");}
// 现代 switch 表达式 (C# 8+)string weatherDescription = temperature switch { < 0 => "结冰", > 30 => "炎热", _ => "适中" // _ 是弃元模式,充当默认值};// for 循环for (int i = 0; i < 3; i++) { Console.WriteLine($"For 循环迭代: {i}");}
// foreach 循环(用于集合)var names = new List<string> { "Ana", "Bob", "Charlie" };foreach (var name in names) { Console.WriteLine($"你好, {name}!");}
// while 循环int countdown = 3;while (countdown > 0) { Console.WriteLine(countdown--);}
// do-while 循环(至少执行一次)do { // ...} while (condition);7. 集合(常用)
Section titled “7. 集合(常用)”// 数组(固定大小)int[] numbers = { 1, 2, 3, 4, 5 };numbers[0] = 10; // 通过索引访问
// 列表(动态大小)using System.Collections.Generic;var fruits = new List<string> { "Apple" };fruits.Add("Banana");fruits.Remove("Apple");
// 字典(键值对)var userAges = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 }};int bobsAge = userAges["Bob"];public int Add(int a, int b) { return a + b;}
// 表达式体方法(用于简单、单行方法)public int Multiply(int a, int b) => a * b;9. 类和对象
Section titled “9. 类和对象”public class Car { // 带有自动实现的 getter/setter 的属性 public string Color { get; set; } public int Year { get; }
// 构造函数 public Car(int year, string color) { Year = year; Color = color; }
// 方法 public void StartEngine() => Console.WriteLine("引擎已启动!");}
// 创建一个对象(实例化)var myCar = new Car(2023, "Red");myCar.StartEngine();10. 记录类型 (C# 9+)
Section titled “10. 记录类型 (C# 9+)”记录类型用于创建具有基于值相等性的不可变数据类型。
// 位置记录类型 - 用于不可变类型的简洁语法public record Person(string FirstName, string LastName);
var person1 = new Person("John", "Doe");var person2 = new Person("John", "Doe");Console.WriteLine(person1 == person2); // True
// 使用 'with' 表达式进行非破坏性修改var person3 = person1 with { LastName = "Smith" };Console.WriteLine(person3.LastName); // Smith11. 异常处理
Section titled “11. 异常处理”try { int result = 10 / 0;} catch (DivideByZeroException ex) { Console.WriteLine("错误: 不能除以零。"); // 记录异常: Console.WriteLine(ex.Message);} finally { Console.WriteLine("此块总是执行。");}12. async 和 await
Section titled “12. async 和 await”用于编写响应式、非阻塞的异步代码。
public async Task<string> FetchDataAsync() { using var client = new HttpClient(); Console.WriteLine("开始下载..."); // await 暂停方法执行,但不会阻塞线程 string data = await client.GetStringAsync("https://api.example.com/data"); Console.WriteLine("下载完成。"); return data;}13. LINQ(语言集成查询)
Section titled “13. LINQ(语言集成查询)”用于以声明性方式查询集合。
using System.Linq;
var numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// 方法语法(最常用)var evenSquares = numbers.Where(n => n % 2 == 0) .Select(n => n * n) .ToList(); // [4, 16, 36, 64, 100]
// 查询语法(类似 SQL)var oddNumbers = from n in numbers where n % 2 != 0 select n;14. 可为空引用类型 (NRTs, C# 8+)
Section titled “14. 可为空引用类型 (NRTs, C# 8+)”有助于在编译时防止 NullReferenceException。在 .csproj 文件中启用 <Nullable>enable</Nullable> 即可。
// 启用 NRTs 后:
string nonNullableName = "Valid Name";// nonNullableName = null; // 生成编译器警告
string? nullableName = null; // '?' 表示这可以是 null
// 在使用可为空类型之前,必须检查是否为 nullif (nullableName != null) { Console.WriteLine(nullableName.Length);}
// 或使用 null 条件运算符Console.WriteLine(nullableName?.Length);15. 字符串操作
Section titled “15. 字符串操作”// 字符串内插string name = "World";string greeting = $"Hello, {name}!";
// 常用方法string text = " Some Text ";text.ToUpper(); // " SOME TEXT "text.Trim(); // "Some Text"text.Contains("Text"); // truetext.Replace("Some", "More"); // " More Text "
// 检查是否为 null 或空/空白字符串string.IsNullOrEmpty(name); // Falsestring.IsNullOrWhiteSpace(" "); // True16. 文件 I/O(使用 System.IO)
Section titled “16. 文件 I/O(使用 System.IO)”// 现代异步文件操作string filePath = "myFile.txt";
// 写入文件await File.WriteAllTextAsync(filePath, "Hello from C#!");
// 从文件读取string content = await File.ReadAllTextAsync(filePath);
// 追加到文件await File.AppendAllTextAsync(filePath, "\nThis is a new line.");