如何在 C# 8 中使用 Index 和 Range
本文轉(zhuǎn)載自微信公眾號(hào)「 碼農(nóng)讀書」,作者 碼農(nóng)讀書 。轉(zhuǎn)載本文請(qǐng)聯(lián)系 碼農(nóng)讀書公眾號(hào)。
C# 8 中有幾個(gè)比較好玩的新特性,比如下面的這兩個(gè):System.Index 和 System.Range,分別對(duì)應(yīng)著索引和切片操作,這篇文章將會(huì)討論這兩個(gè)類的使用。
System.Index 和 System.Range 結(jié)構(gòu)體
可以用它們?cè)谶\(yùn)行時(shí)對(duì)集合進(jìn)行 index 和 slice,下面就是 System.Index 結(jié)構(gòu)體的定義。
- namespace System
- {
- public readonly struct Index
- {
- public Index(int value, bool fromEnd);
- }
- }
然后就是 System.Range 結(jié)構(gòu)體的定義。
- namespace System
- {
- public readonly struct Range
- {
- public Range(System.Index start, System.Index end);
- public static Range StartAt(System.Index start);
- public static Range EndAt(System.Index end);
- public static Range All { get; }
- }
- }
使用 System.Index 從尾部向前對(duì)集合進(jìn)行索引
在 C# 8.0 之前沒有任何方式可以從集合的尾部向前進(jìn)行索引,現(xiàn)在你可以使用 ^ 操作符實(shí)現(xiàn)對(duì)集合的從后往前索引,如下代碼所示:
- System.Index operator ^(int fromEnd);
接下來用一個(gè)例子來理解該操作符的使用,考慮下面的string數(shù)組。
- string[] cities = { "Kolkata", "Hyderabad", "Bangalore", "London", "Moscow", "London", "New York" };
接下來的代碼片段展示了如何使用 ^ 運(yùn)算符來獲取 cities 集合的最后一個(gè)元素。
- var city = cities[^1];
- Console.WriteLine("The selected city is: " + city);
下面是完整的可供參考的代碼:
- public static void Main(string[] args)
- {
- string[] cities = { "Kolkata", "Hyderabad", "Bangalore", "London", "Moscow", "London", "New York" };
- var city = cities[^1];
- Console.WriteLine("The selected city is: " + city);
- Console.ReadLine();
- }
使用 System.Range 來提取子序列
你可以使用 System.Range 從 array 或者 span 類型上提取子集合,下面的代碼展示了如何使用 range 和 index 來提取 string 的最后六個(gè)字符。
- class Program
- {
- public static void Main(string[] args)
- {
- string str = "Hello World!";
- Console.WriteLine(str[^6..]);
- Console.ReadLine();
- }
- }
接下來是一個(gè)如何從 array 上提取子集合的例子。
- public static void Main(string[] args)
- {
- int[] integers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
- var slice = integers[1..5];
- foreach (int i in slice)
- {
- Console.WriteLine(i);
- }
- Console.ReadLine();
- }
從圖中可以看出,輸出的數(shù)字為 1,2,3,4,即表示是一個(gè) [) 的區(qū)間。
在 C#8 之前沒有這樣非常語義化的方式對(duì)集合進(jìn)行 index 和 range,現(xiàn)在不一樣了,你可以使用 ^ 和 .. 這兩個(gè)語法糖,讓你的代碼更加干凈,可讀,易維護(hù)。
譯文鏈接:https://www.infoworld.com/article/3532284/how-to-use-indices-and-ranges-in-csharp-80.html