-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathCSharp13GrammarExercise.cs
138 lines (105 loc) · 3.09 KB
/
CSharp13GrammarExercise.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
using System.Runtime.CompilerServices;
namespace HelloDotNetGuide.CSharp语法
{
public class CSharp13GrammarExercise
{
#region params 集合
public static void SpanDataPrintRun()
{
Span<int> originalSpan = [1, 2, 3, 4, 5];
SpanDataPrint(originalSpan);
}
public static void SpanDataPrint<T>(params Span<T> spans)
{
for (int i = 0; i < spans.Length; i++)
{
Console.WriteLine(spans[i]);
}
}
#endregion
#region 新增Lock锁对象
private object _oldLock = new object();
private System.Threading.Lock _newLock = new System.Threading.Lock();
public void LockTest()
{
lock (_oldLock)
{
Console.WriteLine("Old lock");
}
lock (_newLock)
{
// 传统 lock 语法(优化版)
}
using (_newLock.EnterScope())
{
// 作用域自动释放(推荐写法)
}
_newLock.Enter();
try
{
// 显式 Enter/Exit 调用
}
finally { _newLock.Exit(); }
if (_newLock.TryEnter())
{
try
{
// 非阻塞尝试获取锁
}
finally { _newLock.Exit(); }
}
}
#endregion
#region 新的转义序列
public static void NewEscapeSequence()
{
Console.WriteLine("[31m红色文本[0m");
// C# 13 之前
Console.WriteLine("\u001b[31m红色文本\u001b[0m"); //输出红色文字
// C# 13 中
Console.WriteLine("\e[31m红色文本\e[0m");//功能相同,语法更简洁
}
#endregion
#region 隐式索引访问
public class Numbers
{
public int[] Datas { get; set; } = new int[8];
}
public static void ImplicitIndexAccess()
{
var countdown = new Numbers()
{
Datas =
{
[1] = 0,
[2] = 1,
// 从 C# 13 开始可以执行下面方式赋值
[^3] = 2,
[^4] = 3,
[^5] = 4
}
};
}
#endregion
#region 重载解析优先级
[OverloadResolutionPriority(1)] //优先调用
public static void PrintWay(params int[] numberList) { }
public static void PrintWay(params ReadOnlySpan<int> numberList) { }
#endregion
}
#region partial类型中现在允许使用部分属性和索引器
public partial class MyClass
{
public partial string Name { get; set; }
}
public partial class MyClass
{
private string _name;
public partial string Name
{
get => _name;
set => _name = value;
}
}
#endregion
}