比初恋还甜的c#语法糖

前言

持续收集和整理一些C#或甜或咸的语法糖,一些奇怪的冷知识,逆天的用法.

???????????

?有一堆用法,浅浅总结一些稍微有意思的

可为空的值类型

在c#2.0中引入了可为空的值类型,在值类型后加?表示可为空.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int? a = null;
int[]? b = null;
int?[]? c = null;
bool? boolVar = null;
List<int>? list = null;
List<int?>? list2 = null;

var wtf = new int?[]?[]//甚至可以这么写???
{
new int?[] { 1, 2, 3 },
null,
new int?[] { 4, 5, null }
};

if(a.HasValue)
Console.WriteLine(a.Value);
if (a < 10) //(null < 10) = true)有null的情况下都是false.不推荐这么写
Console.WriteLine("a is less than 10");
if (boolVar.HasValue && boolVar.Value) //当不为null且为true时才执行
Console.WriteLine("d is true");
if (boolVar == true)//推荐这么写代替if(d.HasValue && d.Value)
Console.WriteLine("d is true");

可为空的引用类型

在c#8.0中引入了可为空的引用类型,在引用类型后加?表示可为空.

问题在于:引用类型本身就可以为空,为何还要加入可为空的引用类型?

1
2
3
4
5
6

class A
{
public int X { get; set; }
public string? Name { get; set; }
}

以下内容来源于AI:

在C# 8.0中引入了可为空的引用类型(nullable reference types)是为了帮助开发者更好地处理引用类型可能为null的情况,以减少空引用异常(NullReferenceException)的发生。尽管引用类型本身可以是空的(null),但在引用类型上添加了可为空的标记后,编译器将会对空引用的使用进行更严格的检查,从而帮助开发者避免潜在的空引用问题。
通过使用可为空的引用类型,开发者可以更清晰地表达代码的意图,以及将空引用作为一种可能性考虑进去。在现有的代码中使用可为空的引用类型可能会引入一些警告和错误,这是因为编译器会对潜在的空引用问题进行更严格的检查,需要开发者逐步修改代码以符合新的规则。
总的来说,可为空的引用类型是C# 8.0中引入的一项语言功能,旨在提高代码的清晰度和安全性,减少空引用异常的发生,并帮助开发者更好地处理引用类型的空值问题。

空引用传播

在c#6.0中引入了空引用传播,可以有效减少代码量.可以说是?最常用到的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
if (school != null)
{
if (school.@class != null)
{
if (school.@class.GetStudent() != null)
{
school.@class.GetStudent().IsCoding();
}
}
}

//相当于
school?.@class?.GetStudent()?.IsCoding();

//?[]
var name = school?.@class?.GetStudent()?.name?[0];//name推断类型:char?

空引用传播还可以支持委托等,在此不再演示

?? 空合并运算符

??运算符,可以将左侧的表达式的值,如果不为null,则返回左侧的值,否则返回右侧的值.

1
2
3
4
5
6
7
8
9
10
int? a = null;
int b = 10;
int c = a?? b; //c = 10

string? d = null;
string e = "world";
string f = d?? e; //f = "world"

//??可以抛出异常
string g = d ?? throw new ArgumentNullException("d");

??= 空合并赋值运算符

??=运算符,可以将左侧的表达式的值,如果不为null,则将左侧的值赋值给右侧的变量,否则什么都不做.

1
2
3
4
5
6
int? a   = null;
a ?? = 10; //a = 10

string? b = null;
b ?? = "hello"; //b = "hello"

爱吃的糖果

=>

=> 也是一个常用的语法糖,可以用来简化代码,让代码更加简洁.

匿名函数

=> lamda表达式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Func<int, int, int> example = (x, y) => x + y;

public void Example()
{
Action action = null;
action += () =>{Console.WriteLine("Hello");};

Action<int,string> action2 = null;
action2 += (x,y) => {
x = x + 1;
Console.WriteLine(x);
x = x + 1;
Console.WriteLine(x+y);
};
}

属性与字段

=> 语法糖

1
2
3
4
5
6
7
8
9
class Class{
public int X { get; set; } = 3;
public int Y { get; set; } = 5;

public int Sum => X + Y;

public bool confuse => X <= Y;//挺好看的
}

一些小糖果

数字分割符 _

1
2
3
4
5
//以下代码
int num = 1000000;
//可以写成
int num = 1_000_000;
//是不是好看多了

参考

https://source.dot.net/
https://www.bilibili.com/video/BV15X4y187br/?p=1&vd_source=e83b8f8e3c1120e91a8d3bbe191efb81
https://zhuanlan.zhihu.com/p/429654880?utm_psn=1760445952731852800