c#8.0+ 运算符
从末尾运算符 ^ 开始索引
^
运算符在 C# 8.0 和更高版本中提供,指示序列末尾的元素位置。 对于长度为 length
的序列,^n
指向与序列开头偏移 length - n
的元素。 例如,^1
指向序列的最后一个元素,^length
指向序列的第一个元素。
int[] xs = new[] { 0, 10, 20, 30, 40 }; int last = xs[^1]; Console.WriteLine(last); // output: 40 var lines = new List<string> { "one", "two", "three", "four" }; string prelast = lines[^2]; Console.WriteLine(prelast); // output: three string word = "Twenty"; Index toFirst = ^word.Length; char first = word[toFirst]; Console.WriteLine(first); // output: T
范围运算符
运算符在 C# 8.0 和更高版本中提供,指定索引范围的开头和末尾作为其操作数。 左侧操作数是范围的包含性开头。 右侧操作数是范围的不包含性末尾。 任一操作数都可以是序列开头或末尾的索引,如以下示例所示:
int[] numbers = new[] { 0, 10, 20, 30, 40, 50 }; int start = 1; int amountToTake = 3; int[] subset = numbers[start..(start + amountToTake)]; Display(subset); // output: 10 20 30 int margin = 1; int[] inner = numbers[margin..^margin]; Display(inner); // output: 10 20 30 40 string line = "one two three"; int amountToTakeFromEnd = 5; Range endIndices = ^amountToTakeFromEnd..^0; string end = line[endIndices]; Console.WriteLine(end); // output: three void Display<T>(IEnumerable<T> xs) => Console.WriteLine(string.Join(" ", xs));