C# 7.0 添加和增強的功能【基礎篇】( 二 )

具有相同數量參數的多個 Deconstruct 方法是不明確的 。在定義 Deconstruct 方法時,必須小心使用不同數量的參數 。在重載解析過程中,不能區分具有相同數量參數的 Deconstruct 方法 。
四、析構函數區別于構造函數,構造函數又叫構造方法,它是一種特殊的成員函數,它主要用于為對象分配存儲空間,對數據成員進行初始化,也就是就是對類進行初始化 。
析構函數是實現銷毀一個類的實例的方法成員 。析構函數不能有參數,不能任何修飾符而且不能被調用 。
由于析構函數的目的與構造函數的相反,就以相同的名字然后加前綴 ~ 以示區別 。語法如下:
public class ResourceHolder{~ResourceHolder(){// 這里是清理非托管資源的用戶代碼段}}雖然 C#(更確切的說是 CLR)提供了一種新的內存管理機制——自動內存管理機制,資源的釋放是可以通過“垃圾回收器” 自動完成的,一般不需要用戶干預,但在有些特殊情況下還是需要用到析構函數的,如在 C# 中非托管資源的釋放 。
構造函數與析構函數雖然是一個類中形式上較簡單的函數,但它們的使用決非看上去那么簡單,因此靈活而正確的使用構造函數與析構函數能夠更好的管理系統中的資源 。
五、模式匹配“模式匹配”是一種測試表達式是否具有特定特征的方法 。C# 模式匹配提供更簡潔的語法,用于測試表達式并在表達式匹配時采取措施 。
is表達式”目前支持通過模式匹配測試表達式并有條件地聲明該表達式結果 。
switch表達式”允許你根據表達式的首次匹配模式執行操作 。這兩個表達式支持豐富的模式詞匯 。
// is 聲明模式,用于 測試變量類型 并將其分配給 新變量int? maybe = 12;if (maybe is int number)Console.WriteLine($"The nullable int 'maybe' has the value {number}");elseConsole.WriteLine("The nullable int 'maybe' doesn't hold a value");// is 常數模式,將變量與 null 進行比較,not 為一種邏輯模式,在否定模式不匹配時與該模式匹配string? message = "This is not the null string";if (message is not null){Console.WriteLine(message);}// is 測試變量是否與給定類型匹配public static T MidPoint<T>(IEnumerable<T> sequence){if (sequence is IList<T> list)return list[list.Count / 2];else if (sequence is null)throw new ArgumentNullException(nameof(sequence), "Sequence can't be null.");else{int halfLength = sequence.Count() / 2 - 1;if (halfLength < 0) halfLength = 0;return sequence.Skip(halfLength).First();}}// switch 測試變量(枚舉、常量...)找到特定值的匹配項,如下是通過枚舉類型public State PerformOperation(Operation command) =>command switch{Operation.SystemTest => RunDiagnostics(),Operation.Start => StartSystem(),Operation.Stop => StopSystem(),Operation.Reset => ResetToReady(),_ => throw new ArgumentException("Invalid enum value for command", nameof(command)),//最終 _ 案例為與所有數值匹配的棄元模式};// switch 使用關系模式測試如何將數值與常量進行比較string WaterState2(int tempInFahrenheit) =>tempInFahrenheit switch{< 32 => "solid",32 => "solid/liquid transition",< 212 => "liquid",212 => "liquid / gas transition",_ => "gas",//最終 _ 案例為與所有數值匹配的棄元模式};// switch 檢查一個對象的多個屬性的模式public decimal CalculateDiscount(Order order) =>order switch{{ Items: > 10, Cost: > 1000.00m } => 0.10m,// ( > 10,> 1000.00m) => 0.10m, // 等效 寫法// 如果 Order 類型定義了適當的 Deconstruct 方法,則可以省略模式的屬性名稱,并使用析構檢查屬性{ Items: > 5, Cost: > 500.00m } => 0.05m,{ Cost: > 250.00m } => 0.02m,null => throw new ArgumentNullException(nameof(order), "Can't calculate discount on null order"),var someObject => 0m,};// is 使用列表模式檢查列表或數組中的元素public void MatchElements(int[] array){if (array is [0,1]) // 屬于二進制數字Console.WriteLine("Binary Digits");else if (array is [1,1,2,3,5,8, ..])// 屬于斐波那契數列Console.WriteLine("array looks like a Fibonacci sequence");else //數列無法識別Console.WriteLine("Array shape not recognized");}六、本地函數本地函數是一種嵌套在另一成員中的類型的私有方法 。僅能從其包含成員中調用它們 。
可以聲明和調用本地函數的地方:
??方法(尤其是迭代器方法和異步方法)、構造函數、屬性訪問器、事件訪問器、匿名方法、Lambda 表達式、終結器、其他本地函數等 。
以下示例定義了一個名為 AppendPathSeparator 的本地函數,該函數對于名為 

推薦閱讀