歷史回顧 - C# 13 新功能盤點
| | | 0 | |
參考資料:微軟官方文件 C# 13
C# 13 與 .NET 9 SDK 於 2024 一起釋出。
- 集合運算式可作為 params 參數來源
方法、建構式與運算子支援以集合運算式作為 params 參數來源,寫法更簡潔,算是語法糖吧。void Log(params List<string> messages) { /* IEnumerable-like consume */ } var logs = Log(["init", "start", "ready"]); // 集合運算式供給 params 集合 - 新 lock 類型與語意
新增 System.Threading.Lock 類別,與 lock 語法整合並提供 Enter、TryEnter、EnterScope、Exit 與 IsHeldByCurrentThread 等 API,帶來更清楚與安全的同步控制。
使用 EnterScope() 取得可 using 的範圍物件,離開 using 自動釋放,減少遺漏 Exit 的風險與樣板程式碼。比過去 自己 new object() 給 lock 鎖定更清楚易讀。using System.Threading; var myLock = new Lock(); using (myLock.EnterScope()) { // 臨界區 } // 自動釋放 // 或傳統寫法 myLock.Enter(); try { // 臨界區 } finally { if (myLock.IsHeldByCurrentThread) myLock.Exit(); } \eESC 表示法
新增 \e 代表 ESC (U+001B),比起 \u001B 或 \x1B 更簡潔與易讀,常見於終端色彩或控制碼。\\ ANSI Escape Code 控制顏色 Console.WriteLine($"\x1b[48;2;127;127;255m #7f7fff \x1b[0mA{esc}B"); \\ 使用 \e 取代 \x1b Console.WriteLine($"\e[48;2;127;127;255m #7f7fff \e[0mA{esc}B");- 提升方法群組的自然型別推斷精準度
開發團隊改進了程式邏輯,減少需要手動轉型到特定委派的情況,降低了因模稜兩可必須明確 cast 的機率,讓 API 與 LINQ 委派用起來更簡單。推斷原則class C { public static void Log(string s) { } } var f = C.Log; // C# 13 能推斷 f 型別為 Action<string> Action<string> g = C.Log; - 物件初始器中的隱式索引子存取
物件初始器可直接使用索引子與從尾 ^ 運算子,初始化集合或具索引子的型別。var countdown = new TimerRemaining() { buffer = { [^1] = 0, [^2] = 1, [^3] = 2, [^4] = 3, [^5] = 4, } }; public class TimerRemaining { public int[] buffer { get; set; } = new int[5]; } - 在迭代器/非同步中可啟用 ref locals 與 unsafe
C# 13 放寬限制,允許在 iterator (yield) 與 async 方法中使用 ref locals 與 unsafe,便於高效資料處理場景。(需留意生命週期安全)async Task ProcessAsync(Span<int> s) { ref int head = ref s; head++; await Task.Yield(); } - ref struct 可實作介面
ref struct 也可實作介面,讓以堆疊為基礎的型別也能提供合約與多型使用情境,例如高效序列化或解析器的管線元件。 - 允許 ref struct 作為泛型型別參數實際引數
泛型可接受 ref struct 作為型別參數,引入更廣的高效能泛型抽象,但受限於使用位置必須符合 ref struct 規範,特別適用以Span<T>或自訂 ref struct 為核心的泛型容器或演算法。 - partial 型別允許部分屬性與索引子
partial 類別/結構也可將同一個屬性或索引子的宣告與實作放在不同檔案。(過去有方法可以做法)public partial class C { // Declaring declaration public partial string Name { get; set; } } public partial class C { // implementation declaration: private string _name; public partial string Name { get => _name; set => _name = value; } } - Overload Resolution Priority
新增多載解析優先權,開發者可將某一多載標記為較佳選擇([OverloadResolutionPriority(1)],數字愈大愈優先),減少呼叫端因模稜兩可而須加型別註解的情況。
A concise overview of C# 13’s key features.
Comments
Be the first to post a comment