100个 C# 技巧,我希望我早知道的(第1部分)
发布: (2026年4月6日 GMT+8 04:07)
4 分钟阅读
原文: Dev.to
Source: Dev.to

改善代码的现代 C# 特性
1. 使用主构造函数
public class Person(string name, int age)
{
public string Name { get; } = name;
public int Age { get; } = age;
}更简洁、更短、更易维护。
2. 使用集合表达式
List numbers = [1, 2, 3, 4, 5];少敲键,代码更清晰。
3. 使用 nameof 进行更安全的重构
Console.WriteLine(nameof(Person.Name));编译器现在可以帮助你捕获错误。
4. 使用空合并运算符提升代码安全性
string name = person.Name ?? "Unknown";简单且安全。
5. 模式匹配 = 更清晰的逻辑
if (person is { Age: > 18, Name: not null })
{
Console.WriteLine($"{person.Name} is an adult.");
}6. 优先使用字符串插值
string message = $"Hello, {person.Name}!";7. 使用元组代替额外的类
public (string, int) GetPersonInfo()
{
return ("Alice", 30);
}轻量且高效。
8. 使用局部函数提升结构化程度
void Process()
{
int Add(int a, int b) => a + b;
Console.WriteLine(Add(1, 2));
}9. 用 using var 替代嵌套块
using var reader = new StreamReader("file.txt");更简洁的资源管理。
10. 使用 IAsyncEnumerable 进行流式数据处理
public async IAsyncEnumerable GetData()
{
for (int i = 0; i
}Switch Statements
string result = age switch
{
> 18 => "Adult",
_ => "Minor"
};14. 使用 with 更新对象
var updated = person with { Age = 31 };15. 文件作用域的命名空间减少噪音
namespace MyApp;文件瞬间更整洁。
16. 使用 required 提升模型安全性
public class Person
{
public required string Name { get; set; }
}17. 只读初始化属性实现不可变性
public string Name { get; init; }18. 全局 using 消除重复
global using System;19. CallerArgumentExpression 用于调试
public void Validate(bool condition,
[CallerArgumentExpression("condition")] string msg = "")
{
if (!condition) throw new Exception(msg);
}20. 默认接口方法
public interface ILogger
{
void Log(string msg) => Console.WriteLine(msg);
}性能与进阶技巧
21. 使用 Span 实现高性能
Span numbers = stackalloc int[10];22. 使用 ArrayPool 减少 GC 压力
var pool = ArrayPool.Shared;
var arr = pool.Rent(10);
pool.Return(arr);23. 使用 ValueTask 实现轻量级异步
public ValueTask GetValueAsync() => new(42);24. ConfigureAwait 提升性能
await Task.Delay(100).ConfigureAwait(false);25. 使用 Stopwatch 测量性能
var sw = Stopwatch.StartNew();
// code to measure
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);最后感想
这些小改进会随时间累积成大提升。
它们让我的代码:
- 更简洁
- 更快
- 更易维护