C# 的一些好用的语法糖介绍

C# 中有很多语法糖(Syntactic sugar),它们是一些语言特性,使得编写代码更加简洁、易读、更具表现力。

Lambda 表达式:

Lambda 表达式允许你编写简洁的匿名函数。例如:

Func<int, int, int> add = (a, b) => a + b;

自动属性:

简化了属性的定义。编译器会自动创建私有字段并生成 getter 和 setter 方法。

public int Age { get; set; }

集合初始化器:

允许你初始化集合类型,使得代码更加清晰。

var list = new List<int> { 1, 2, 3 };

空值合并运算符:

简化了处理可能为 null 的情况。

string name = null;

string result = name ?? "default";

字符串插值:

允许在字符串中直接插入表达式,更加方便地构建字符串。

string name = "John";

string message = $"Hello, {name}!";

模式匹配:

可以方便地检查对象的类型和属性。

if (obj is MyClass myObj)

{

// 使用 myObj

}

1

2

3

4

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

相关推荐
2601_949847751 分钟前
Flutter for OpenHarmony 剧本杀组队App实战:关于我们页面实现
开发语言·javascript·flutter
轩情吖2 分钟前
Qt多元素控件之QTableWidget
开发语言·c++·qt·表格·控件·qtablewidget
froginwe112 分钟前
PostgreSQL 表达式详解
开发语言
LuminescenceJ5 分钟前
RPC通信中的Context上下文如何跨进程传递消息,gRPC为例分析
开发语言·网络·后端·网络协议·rpc·golang
IT陈图图8 分钟前
Flutter × OpenHarmony 实战:优雅构建确认对话框的组件化方案
开发语言·javascript·flutter
雨季6668 分钟前
Flutter 三端应用实战:OpenHarmony 简易文本末尾字符查看器开发指南
开发语言·javascript·flutter
Lxinccode9 分钟前
python(70) : 网页IDE
开发语言·ide·python·网页ide
zmjjdank1ng10 分钟前
理解bash和shell
linux·运维·开发语言·bash
码界奇点11 分钟前
基于Beego v2与Go语言的网站管理后台系统设计与实现
开发语言·golang·毕业设计·go语言·源代码管理·beego
潇凝子潇11 分钟前
Arthas 火焰图的使用
开发语言·python