日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

如何在 C# 8 中使用 Index 和 Range

發布時間:2023/12/4 C# 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 如何在 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。