C# 的一些好用的语法糖介绍
C# ��有很多语法糖(Syntactic sugar),它们是一些语言特性,使得编写代码更加简洁、易读、更具表现力。
()Lambda 表达式:
Lambda 表达式允许你编写简洁的匿名函数。例如:
()Func add = (a, b) => a + b;
自动属性:
简化了属性的定义。编译器会自动创建私有字段并生成 getter 和 setter 方法。
public int Age { get; set; }
集合初始化器:
允许你初始化集合类型,使得代码更加清晰。
var list = new List { 1, 2, 3 };
空值合并运算符:
简化了处理可能为 null 的情况。
string name = null; string result = name ?? "default";
字符串插值:
允许在字符串中直接插入表达式,更加方便地构建字符串。
string name = "John"; string message = $"Hello, {name}!";
模式匹配:
可以方便地检查对象的类型和属性。
if (obj is MyClass myObj) { // 使用 myObj }
foreach 循环:
简化了遍历集合的过程。
foreach (var item in collection) { // 处理 item }
using 语句:
确保资源在使用完后被释放,使得代码更加健壮。
using (var stream = new FileStream("file.txt", FileMode.Open)) { // 使用 stream }
扩展方法:
允许你在不修改原始类的情况下向现有类添加方法。
public static class StringExtensions { public static bool IsNullOrEmpty(this string str) { return string.IsNullOrEmpty(str); } } // 使用扩展方法 bool result = "test".IsNullOrEmpty();
命名参数:
可以在调用方法时指定参数的名称,增加了可读性。
PrintName(firstName: "John", lastName: "Doe"); static void PrintName(string firstName, string lastName) { Console.WriteLine($"{firstName} {lastName}"); }
可空值类型:
允许基本数据类型表示为可空的,用于表示可能为 null 的值。
int? nullableInt = null;
委托:
委托是一种类型,用于引用方法。它们提供了更灵活的事件处理和回调机制。
delegate int Operation(int x, int y);
不可变性:
使用 readonly 和 const 关键字可以创建不可变字段和常量。
readonly int readOnlyValue = 10; const int constantValue = 5;
模式匹配:
允许在 switch 语句中使用模式来匹配值。
switch (obj) { case MyClass myObj: // 使用 myObj break; case null: // 处理 null break; }
属性表达式:
允许你在编译时动态地访问属性和方法。
string propertyName = nameof(MyClass.MyProperty);
The End