Skip to content

C# - 速查表

本速查表提供了对 C# 基本和现代概念的快速参考。C# 是一种多功能、跨平台的语言,由 .NET 生态系统提供支持,用于构建 Web API、云服务、桌面、移动和游戏应用程序。本指南将帮助您快速掌握开发、面试和考试的关键语法和功能。

现代 C#(.NET 6+)使用顶级语句来简化控制台应用程序的代码。

// 对于简单的程序,不需要 'using System;'、'namespace'、'class' 或 'Main' 方法。
Console.WriteLine("Hello, Modern C#!");
// 这是单行注释。
/*
这是
多行注释。
*/
/// <summary>
/// 这是用于生成文档的 XML 文档注释。
/// </summary>
  • 整数: 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(表示方法签名的一种类型)
// 变量声明
string name = "Alice";
int age = 30;
// 'var' 从值中推断类型
var message = "Hello, World!"; // 编译器知道 'message' 是一个字符串
// 常量声明(值必须在编译时已知)
const double Pi = 3.14159;
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);
// 数组(固定大小)
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;
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();

记录类型用于创建具有基于值相等性的不可变数据类型。

// 位置记录类型 - 用于不可变类型的简洁语法
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); // Smith
try {
int result = 10 / 0;
} catch (DivideByZeroException ex) {
Console.WriteLine("错误: 不能除以零。");
// 记录异常: Console.WriteLine(ex.Message);
} finally {
Console.WriteLine("此块总是执行。");
}

用于编写响应式、非阻塞的异步代码。

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;
}

用于以声明性方式查询集合。

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;

有助于在编译时防止 NullReferenceException。在 .csproj 文件中启用 <Nullable>enable</Nullable> 即可。

// 启用 NRTs 后:
string nonNullableName = "Valid Name";
// nonNullableName = null; // 生成编译器警告
string? nullableName = null; // '?' 表示这可以是 null
// 在使用可为空类型之前,必须检查是否为 null
if (nullableName != null) {
Console.WriteLine(nullableName.Length);
}
// 或使用 null 条件运算符
Console.WriteLine(nullableName?.Length);
// 字符串内插
string name = "World";
string greeting = $"Hello, {name}!";
// 常用方法
string text = " Some Text ";
text.ToUpper(); // " SOME TEXT "
text.Trim(); // "Some Text"
text.Contains("Text"); // true
text.Replace("Some", "More"); // " More Text "
// 检查是否为 null 或空/空白字符串
string.IsNullOrEmpty(name); // False
string.IsNullOrWhiteSpace(" "); // True
// 现代异步文件操作
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.");