C#8中的范围和索引类型是什么? [英] What are Range and Index types in C# 8?
问题描述
在C#8中,向系统名称空间添加了两种新类型: System.Index
和 System.Range
.
In C# 8, two new types are added to the System namespace: System.Index
and System.Range
.
它们如何工作,什么时候可以使用它们?
How do they work and when can we use them?
推荐答案
它们用于索引和切片.来自微软的博客:
They're used for indexing and slicing. From Microsoft's blog:
索引:
Index i1 = 3; // number 3 from beginning
Index i2 = ^4; // number 4 from end
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.WriteLine($"{a[i1]}, {a[i2]}"); // "3, 6"
范围(切片)
我们还引入了范围类型,它由两个索引组成,一个用于开始,一个用于结束,并且可以用x..y编写范围表达式.然后,您可以使用Range进行索引以产生一片:
We’re also introducing a Range type, which consists of two Indexes, one for the start and one for the end, and can be written with a x..y range expression. You can then index with a Range in order to produce a slice:
var slice = a[i1..i2]; // { 3, 4, 5 }
您可以在 Array
, String
, [ReadOnly] Span
和 [ReadOnly] Memory
类型中使用它们,因此您还有另一种制作子字符串的方法:
You can use them in Array
, String
, [ReadOnly]Span
and [ReadOnly]Memory
types, so you have another way to make substrings:
string input = "This a test of Ranges!";
string output = input[^7..^1];
Console.WriteLine(output); //Output: Ranges
您还可以省略范围的第一个或最后一个索引:
You can also omit the first or last Index of a Range:
output = input[^7..]; //Equivalent of input[^7..^0]
Console.WriteLine(output); //Output: Ranges!
output = input[..^1]; //Equivalent of input[0..^1]
Console.WriteLine(output); //Output: This a test of Ranges
您还可以将范围保存到变量中,并在以后使用它们:
You can also save ranges to variables and use them later:
Range r = 0..^1;
output = input[r];
Console.WriteLine(output);
这篇关于C#8中的范围和索引类型是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!