C# 常用语法速查表
把 C# 日常开发最常用的语法整理成速查,写 .NET 代码时对照查。
返回 编程语言类与接口 7
public class MyClass { }类定义
public interface IMyInterface { void Method(); }接口定义
public class Derived : Base, IMyInterface { }继承与实现接口
public abstract class AbstractClass { }抽象类
public sealed class SealedClass { }密封类(不可继承)
public static class Utils { }静态类
public record Person(string Name, int Age);记录类型(C# 9)
属性与方法 6
public int Age { get; set; }自动属性
public string Name { get; init; }只初始化属性(C# 9)
public int Age => _age;只读属性(表达式体)
public void Method() { }方法定义
public int Add(int a, int b) => a + b;表达式体方法
public event EventHandler MyEvent;事件定义
LINQ 查询 8
var result = list.Where(x => x > 5);过滤
var result = list.Select(x => x * 2);映射
var result = list.OrderBy(x => x.Age);排序
var result = list.GroupBy(x => x.Category);分组
var result = list.First(x => x.Id == 1);查找第一个
var result = list.Any(x => x > 0);是否存在
var result = list.Sum(x => x.Price);求和
var result = list.Aggregate((a, b) => a + b);聚合
异步编程 6
public async Task<int> GetDataAsync() { }异步方法
await Task.Delay(1000);异步延迟
var result = await httpClient.GetStringAsync(url);异步 HTTP 请求
Task.Run(() => { });后台线程执行
await Task.WhenAll(task1, task2);并行等待多个任务
CancellationTokenSource cts = new();取消令牌
泛型与委托 6
public class Stack<T> { }泛型类
public T Max<T>(T a, T b) where T : IComparable<T> { }泛型约束
public delegate void MyDelegate(string msg);委托定义
public event Action<string> OnMessage;Action 委托
public Func<int, int, int> add = (a, b) => a + b;Func 委托
public Predicate<int> isPositive = x => x > 0;Predicate 委托
集合与字典 6
List<int> list = new() { 1, 2, 3 };列表
Dictionary<string, int> dict = new();字典
HashSet<int> set = new() { 1, 2, 3 };哈希集合
Queue<int> queue = new();队列
Stack<int> stack = new();栈
var tuple = (1, "hello");元组
💡 提示
- LINQ 查询延迟执行,只在枚举结果时才真正执行。
- async/await 是异步编程的核心,避免阻塞 UI 线程。
- C# 9 引入 record 类型,适合不可变数据模型。