当前位置: 首页 > 科技观察

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

时间:2023-03-22 13:47:27 科技观察

文章转载请联系码农阅读公众号。C#8中有几个有趣的新特性,比如下面两个:System.Index和System.Range,分别对应索引和切片操作。本文将讨论这两个类的使用。System.Index和System.Range结构可用于在运行时对集合进行索引和切片。以下是System.Index结构的定义。namespaceSystem{publicreadonlystructIndex{publicIndex(intvalue,boolfromEnd);}}然后是System.Range结构的定义。namespaceSystem{publicreadonlystructRange{publicRange(System.Indexstart,System.Indexend);publicstaticRangeStartAt(System.Indexstart);publicstaticRangeEndAt(System.Indexend);publicstaticRangeAll{get;}}}在C#中使用System.Index从尾到前索引集合之前8.0,无法从集合末尾向前索引。现在可以使用^运算符从后向前对集合进行索引,如下代码所示:System.Indexoperator^(intfromEnd);接下来,使用示例要了解此运算符的用法,请考虑以下字符串数组。string[]cities={"Kolkata","Hyderabad","Bangalore","London","Moscow","London","NewYork"};以下代码片段显示了如何使用^运算符获取城市集合的最后一个元素。varcity=cities[^1];Console.WriteLine("Theselectedcityis:"+city);以下为完整代码供参考:};varcity=cities[^1];Console.WriteLine("Theselectedcityis:"+city);Console.ReadLine();}使用System.Range提取子序列您可以使用System.Range从数组中提取子集或span类型,下面的代码展示了如何使用range和index来提取string的最后六个字符。classProgram{publicstaticvoidMain(string[]args){stringstr="HelloWorld!";Console.WriteLine(str[^6..]);Console.ReadLine();}}接下来是如何从数组中提取子集合的例子.publicstaticvoidMain(string[]args){int[]integers={0,1,2,3,4,5,6,7,8,9};varslice=integers[1..5];foreach(intiinslice){Console.WriteLine(i);}Console.ReadLine();}从图中可以看出输出的数字是1,2,3,4,表示是[)的一个区间。在C#8之前,没有这种非常语义化的方法来索引和范围集合。现在不同了。您可以使用^和..这两个语法糖来使您的代码更加简洁、可读和易于维护。翻译链接:https://www.infoworld.com/article/3532284/how-to-use-indices-and-ranges-in-csharp-80.html

最新推荐
猜你喜欢