C# 语法糖
语法糖:是 C# 编程语言中为了简化代码和提高代码可读性而引入的一系列语言特性。这些特性在编译时会被转换成更基本的代码形式,但在编写代码时提供了更加简洁和直观的方式。
1.表达式体属性:使用 => 运算符定义属性的 getter 或 setter。
public string FullName => FirstName + " " + LastName;
2.隐式类型局部变量(var 关键字):编译器根据初始化表达式推断变量的类型。
var number = 42; // 推断为 int 类型
3.Lambda 表达式:定义匿名函数的简洁方式。
Func<int, int, int> add = (x, y) => x + y;
4.表达式体成员:用于方法和委托。
public int Sum(int x) => x * x;
5.字符串插值:在字符串中嵌入变量或表达式的值。
string msg = $"Hello, {name}!";
6.空合并运算符(??):当左侧操作数为 null 时,返回右侧操作数的值。
string result = value ?? "Default Value";
7.异步/等待(async/await):简化异步编程模型。
public async Task<string> GetWebPageAsync(string url){
using (var client = new HttpClient())
{return await client.GetStringAsync(url);}
}
8.使用语句(using 声明):自动释放资源,如文件和网络连接。
using (var file = new StreamReader("file.txt")){
// 读取文件内容} // file 对象在这里会被自动释放
MyMethod(name: "Alice", age: 30);
public static class StringExtensions{
public static string ToUpperInvariant(this string s)
{
return s.ToUpper(CultureInfo.InvariantCulture);
}
}
using System.Collections.Generic;using List = System.Collections.Generic.List<int>;
// 定义别名List numbers = new List(); // 使用别名
string text = null;int? length = text?.Length; // 如果 text 为 null,则 length 为 null;否则为 text 的长度
var person = (Name: "Alice", Age: 30);Console.WriteLine(person.Name); // 输出 "Alice"
object obj = "hello";if (obj is string s){
Console.WriteLine(s.ToUpper());
// 输出 "HELLO"}
int[] numbers = { 0, 1, 2, 3, 4, 5 };int[] subArray = numbers[1..4]; // { 1, 2, 3 }
using System;Console.WriteLine("Hello, World!"); // 直接在顶层编写的语句
int? age = null;if (age.HasValue){
// 处理非空值的情况}
string name = "Alice";Console.WriteLine(nameof(name)); // 输出 "name"
using var file = new StreamReader("file.txt");// 使用 file 进行操作...// 在代码块结束时,file 会被自动释放
var query = from p in people
where p.Age > 18
select p.Name;
Console.WriteLine("Debug mode is enabled.");