Requirements: To define a collection, we need to get the last element of the collection, the code is usually array[array. Length - 1] In this way, C# 8.0 introduces a new index expression meaning "from the last". The feature will introduce a new unary prefix "hat" operator.
review
System index
C# can't index a collection from the end, but most indexers use the concept of "start with", or execute the "length-i" expression. We introduced a new index expression that means "from the end". The feature will introduce a new unary prefix "hat" operator. Its single operand must be convertible to System.Int32. It will be reduced to the appropriate System.Index factory method call.
string[] words = new string[]
{ // index from start index from end "The", // 0 ^9 "quick", // 1 ^8 "brown", // 2 ^7 "fox", // 3 ^6 "jumps", // 4 ^5 "over", // 5 ^4 "the", // 6 ^3 "lazy", // 7 ^2 "dog" // 8 ^1 }; // 9 (or words. Length) ^0 With the new syntax, we can easily get the last element object of a collection with the following code:
The index is the same as 0 sequence[0]. The index is the same as ^0 sequence[sequence. Length]。 The expression sequence[^0] does throw an exception, just like sequence[sequence. Length]. For any number n, the index ^n is the samesequence. Length - n。
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
Resources:
The hyperlink login is visible.
The hyperlink login is visible.
(End)
|