^1 在 C# 中作为数组索引(例如 arr[^1])是什么意思?
What is meant by ^1 as array index (e.g. arr[^1]) in C#?
int []arr = new int[4];
arr[^1]; // returns the last element
我正在尝试弄清楚上面的语法。它返回最后一个元素,但为什么呢?
C# 8.0 及以后,声明了 new ranges and indexes
其中^
运算符:
Let's start with the rules for indices. Consider an array sequence. The 0
index is the same as sequence[0]
. The ^0
index is the same as sequence[sequence.Length]
.
因此这是一种反向搜索可索引对象的方法,无需像 sequence[sequence.Length - i]
那样进行迭代。
string[] words = new string[]
{
// index from start index from end
"The", // 0 ^9
"quick", // 1 ^8
"brown", // 2 ^7
"fox", // 3 ^6
"jumped", // 4 ^5
"over", // 5 ^4
"the", // 6 ^3
"lazy", // 7 ^2
"dog" // 8 ^1
}; // 9 (or words.Length) ^0
int []arr = new int[4];
arr[^1]; // returns the last element
我正在尝试弄清楚上面的语法。它返回最后一个元素,但为什么呢?
C# 8.0 及以后,声明了 new ranges and indexes
其中^
运算符:
Let's start with the rules for indices. Consider an array sequence. The
0
index is the same assequence[0]
. The^0
index is the same assequence[sequence.Length]
.
因此这是一种反向搜索可索引对象的方法,无需像 sequence[sequence.Length - i]
那样进行迭代。
string[] words = new string[]
{
// index from start index from end
"The", // 0 ^9
"quick", // 1 ^8
"brown", // 2 ^7
"fox", // 3 ^6
"jumped", // 4 ^5
"over", // 5 ^4
"the", // 6 ^3
"lazy", // 7 ^2
"dog" // 8 ^1
}; // 9 (or words.Length) ^0