前言

在C#8.0中新增了两个新的特性,System.IndexSystem.Range,这是借助对应的两个运算符 ^..,让我们很方便就可以获取序列中某个或一段元素。

正文

System.Index

System.Index表示索引类型,^指定的索引是相对于序列尾端。如^2表示从序列尾端、从右至左的第二个元素。这里始终记住 ^x等价于 list.length - x ,所以如果代码写成 list[^0],那么等价于 list[list.length-0],结果就会抛出异常。下边举例说明。

var list = new[]
{
"爱","情","公","寓","曾","小","贤","胡","一","菲","吕","子","乔","陈","美","嘉"
};

System.Index index1 = 0;
System.Index index2 = ^0;
//var简写
var idx3 = ^1;

//打印 爱
Console.WriteLine(list[idx1]);
//报错
Console.WriteLine(list[idx2]);
//打印 嘉
Console.WriteLine(list[idx3]);
//直接写 ^2 ,打印 美
Console.WriteLine(list[^2]);

System.Range

System.Range表示序列的子范围,使用运算符x..y,表示取序列中x到y的一段数据,但不包括y。再举例说明

var rng1 = ..; //声明一个Range类型的变量
var rng2 = 2..;
var list = new[]
{
"爱","情","公","寓","曾","小","贤","胡","一","菲","吕","子","乔","陈","美","嘉"
};

//取全部,打印 爱情公寓曾小贤胡一菲吕子乔陈美嘉
Console.WriteLine(string.Join("",list[rng1]));

//取2到后边所有,打印 公寓曾小贤胡一菲吕子乔陈美嘉
Console.WriteLine(string.Join("",list[rng2]));

//取2到4,但不包括4,打印 公寓
Console.WriteLine(string.Join("",list[2..4]));

//取开始到4,但不包括4,打印 爱情公寓
Console.WriteLine(string.Join("",list[..4]));

混合使用 Index、Range

var list = new[]
{
"爱","情","公","寓","曾","小","贤","胡","一","菲","吕","子","乔","陈","美","嘉"
};

//取倒数第二个至后边所有,打印 美嘉
//这里 ^0 不会报错,因为范围取值不包括后边
Console.WriteLine(string.Join("",list[^2..^0]));

Console.WriteLine(string.Join("",list[^2..^6]));


to be continued…