|
需求:定义一个集合,我们需要获取集合的最后一个元素,代码通常是 array[array.Length - 1] 这种写法,C# 8.0 引入了一个新的索引表达式,意思是“从最后”。该功能将引入一个新的一元前缀“hat”运算符。
回顾
系统索引
C# 无法从末尾索引集合,但大多数索引器使用“从开始”的概念,或执行“长度 - i”表达式。我们引入了一个新的索引表达式,意思是“从最后”。该功能将引入一个新的一元前缀“hat”运算符。它的单个操作数必须可转换为System.Int32. 它将被降低到适当的System.Index工厂方法调用中。
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 有了新的语法,我们可以很简单的获取集合的最后一个元素对象,代码如下:
索引与 0 相同 sequence[0]。索引与 ^0 相同 sequence[sequence.Length]。表达式sequence[^0]确实会引发异常,就像sequence[sequence.Length]这样。对于任何数字n,索引^n都与相同sequence.Length - n。
Unhandled exception. System.IndexOutOfRangeException: Index was outside the bounds of the array.
参考资料:
超链接登录可见。
超链接登录可见。
(完)
|
上一篇:【实战】.NET/C# 使用 UDP 发送和接受数据下一篇:用powershell进入本地组策略编辑器,并修改保存
|