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

相关推荐
大尚来也7 分钟前
PHP 反序列化漏洞深度解析:从原理利用到 allowed_classes 防御实战
android·开发语言·php
WarrenMondeville9 分钟前
1.Unity面向对象-单一职责原则
unity·设计模式·c#
雕刻刀9 分钟前
ERROR: Failed to build ‘natten‘ when getting requirements to build wheel
开发语言·python
qq_4160187210 分钟前
高性能密码学库
开发语言·c++·算法
小碗羊肉19 分钟前
【从零开始学Java | 第十八篇】BigInteger
java·开发语言·新手入门
宵时待雨21 分钟前
C++笔记归纳14:AVL树
开发语言·数据结构·c++·笔记·算法
执笔画流年呀35 分钟前
PriorityQueue(堆)续集
java·开发语言
山川行38 分钟前
关于《项目C语言》专栏的总结
c语言·开发语言·数据结构·vscode·python·算法·visual studio code
呜喵王阿尔萨斯40 分钟前
C and C++ code
c语言·开发语言·c++
左左右右左右摇晃1 小时前
JDK 1.7 ConcurrentHashMap——分段锁
java·开发语言·笔记