Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

c# 8.0 - What are Range and Index types in C# 8?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

They're used for indexing and slicing. From Microsoft's blog:

Indexing:

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"

Range (slicing):

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 }

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...