C# 8 中有几个比拟好玩的新个性,比方上面的这两个:System.IndexSystem.Range,别离对应着索引和切片操作,这篇文章将会探讨这两个类的应用。

System.Index 和 System.Range 构造体

能够用它们在运行时对汇合进行 indexslice,上面就是 System.Index 构造体的定义。

namespace System{    public readonly struct Index    {        public Index(int value, bool fromEnd);    }}

而后就是 System.Range 构造体的定义。

namespace System{    public readonly struct Range    {        public Range(System.Index start, System.Index end);        public static Range StartAt(System.Index start);        public static Range EndAt(System.Index end);        public static Range All { get; }    }}

应用 System.Index 从尾部向前对汇合进行索引

在 C# 8.0 之前没有任何形式能够从汇合的尾部向前进行索引,当初你能够应用 ^ 操作符实现对汇合的从后往前索引,如下代码所示:

System.Index operator ^(int fromEnd);

接下来用一个例子来了解该操作符的应用,思考上面的string数组。

string[] cities = { "Kolkata", "Hyderabad", "Bangalore", "London", "Moscow", "London", "New York" };

接下来的代码片段展现了如何应用 ^ 运算符来获取 cities 汇合的最初一个元素。

var city = cities[^1];Console.WriteLine("The selected city is: " + city);

上面是残缺的可供参考的代码:

        public static void Main(string[] args)        {            string[] cities = { "Kolkata", "Hyderabad", "Bangalore", "London", "Moscow", "London", "New York" };            var city = cities[^1];            Console.WriteLine("The selected city is: " + city);            Console.ReadLine();        }

应用 System.Range 来提取子序列

你能够应用 System.Range 从 array 或者 span 类型上提取子集合,上面的代码展现了如何应用 range 和 index 来提取 string 的最初六个字符。

    class Program    {        public static void Main(string[] args)        {            string str = "Hello World!";            Console.WriteLine(str[^6..]);            Console.ReadLine();        }    }

接下来是一个如何从 array 上提取子集合的例子。

        public static void Main(string[] args)        {            int[] integers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };            var slice = integers[1..5];            foreach (int i in slice)            {                Console.WriteLine(i);            }            Console.ReadLine();        }

从图中能够看出,输入的数字为 1,2,3,4,即示意是一个 [) 的区间。

在 C#8 之前没有这样十分语义化的形式对汇合进行 index 和 range,当初不一样了,你能够应用 ^.. 这两个语法糖,让你的代码更加洁净,可读,易保护。

译文链接:https://www.infoworld.com/art...

更多高质量干货:参见我的 GitHub: csharptranslate