1. 程式人生 > 其它 >如何在 C# 8 中使用 Index 和 Range

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

技術標籤:jscsspythonjavascript3d

C# 8 中有幾個比較好玩的新特性,比如下面的這兩個:System.IndexSystem.Range,分別對應著索引和切片操作,這篇文章將會討論這兩個類的使用。

System.Index 和 System.Range 結構體

可以用它們在執行時對集合進行 indexslice,下面就是 System.Index 結構體的定義。


namespaceSystem
{
publicreadonlystructIndex
{
publicIndex(intvalue,boolfromEnd);
}
}

然後就是 System.Range

結構體的定義。


namespaceSystem
{
publicreadonlystructRange
{
publicRange(System.Indexstart,System.Indexend);
publicstaticRangeStartAt(System.Indexstart);
publicstaticRangeEndAt(System.Indexend);
publicstaticRangeAll{get;}
}
}

使用 System.Index 從尾部向前對集合進行索引

在 C# 8.0 之前沒有任何方式可以從集合的尾部向前進行索引,現在你可以使用 ^ 操作符實現對集合的從後往前索引,如下程式碼所示:


System.Indexoperator^(intfromEnd);

接下來用一個例子來理解該操作符的使用,考慮下面的string陣列。


string[]cities={"Kolkata","Hyderabad","Bangalore","London","Moscow","London","NewYork"};

接下來的程式碼片段展示瞭如何使用 ^ 運算子來獲取 cities 集合的最後一個元素。


varcity=cities[^1];
Console.WriteLine("Theselectedcityis:"+city);

下面是完整的可供參考的程式碼:


publicstaticvoidMain(string[]args)
{
string[]cities={"Kolkata","Hyderabad","Bangalore","London","Moscow","London","NewYork"};

varcity=cities[^1];
Console.WriteLine("Theselectedcityis:"+city);

Console.ReadLine();
}

使用 System.Range 來提取子序列

你可以使用 System.Range 從 array 或者 span 型別上提取子集合,下面的程式碼展示瞭如何使用 range 和 index 來提取 string 的最後六個字元。


classProgram
{
publicstaticvoidMain(string[]args)
{
stringstr="HelloWorld!";
Console.WriteLine(str[^6..]);

Console.ReadLine();
}
}

接下來是一個如何從 array 上提取子集合的例子。


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 之前沒有這樣非常語義化的方式對集合進行 index 和 range,現在不一樣了,你可以使用 ^.. 這兩個語法糖,讓你的程式碼更加乾淨,可讀,易維護。

譯文連結:https://www.infoworld.com/article/3532284/how-to-use-indices-and-ranges-in-csharp-80.html