C#数组索引 “[^x]” (例如arr[^1])是什么意思

890 阅读1分钟

C# 8.0 及以后,声明了新的范围和索引。 其中 ^ 运算符:让我们从索引的规则开始。 考虑一个数组序列。 0 索引与序列[0] 相同。 ^0 索引与序列[arr.Length] 相同。所以它是一种反向搜索可索引对象的方法,不需要像 arr[arr.Length - i] 那样迭代。

int[] a = new int[]
{
         //    
    1,   // 0     ^3
    2,   // 1     ^2
    3    // 2     ^1
};

Console.WriteLine(a[^1]);
Console.ReadLine();

输出结果:

image.png

内容参考于:stackoverflow.com/questions/6…