如何在 C# 8 中使用 Index 和 Range
C# 8 中有幾個比較好玩的新特性,比如下面的這兩個:System.Index 和 System.Range,分別對應著索引和切片操作,這篇文章將會討論這兩個類的使用。
System.Index 和 System.Range 結構體
可以用它們在運行時對集合進行 index 和 slice,下面就是 System.Index 結構體的定義。
namespace?System {public?readonly?struct?Index{public?Index(int?value,?bool?fromEnd);} }然后就是 System.Range 結構體的定義。
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 從尾部向前對集合進行索引
在 C# 8.0 之前沒有任何方式可以從集合的尾部向前進行索引,現在你可以使用 ^ 操作符實現對集合的從后往前索引,如下代碼所示:
System.Index?operator?^(int?fromEnd);接下來用一個例子來理解該操作符的使用,考慮下面的string數組。
string[]?cities?=?{?"Kolkata",?"Hyderabad",?"Bangalore",?"London",?"Moscow",?"London",?"New?York"?};接下來的代碼片段展示了如何使用 ^ 運算符來獲取 cities 集合的最后一個元素。
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 的最后六個字符。
class?Program{public?static?void?Main(string[]?args){string?str?=?"Hello?World!";Console.WriteLine(str[^6..]);Console.ReadLine();}}接下來是一個如何從 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();}從圖中可以看出,輸出的數字為 1,2,3,4,即表示是一個 [) 的區間。
在 C#8 之前沒有這樣非常語義化的方式對集合進行 index 和 range,現在不一樣了,你可以使用 ^ 和 .. 這兩個語法糖,讓你的代碼更加干凈,可讀,易維護。
譯文鏈接:https://www.infoworld.com/article/3532284/how-to-use-indices-and-ranges-in-csharp-80.html
總結
以上是生活随笔為你收集整理的如何在 C# 8 中使用 Index 和 Range的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 中的动态类型
- 下一篇: 如何在 C# 8 中使用默认接口方法