第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定

如何在 C# 8 中使用 Index 和 Range

標(biāo)簽:
C#

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,现在不一样了,你可以使用 ^.. 这两个语法糖,让你的代码更加干净,可读,易维护。

**更多高质量干货:参见我的 GitHub: [csharptranslate] github.com/ctripxchuang/csharptranslate **

點擊查看更多內(nèi)容
TA 點贊

若覺得本文不錯,就分享一下吧!

評論

作者其他優(yōu)質(zhì)文章

正在加載中
  • 推薦
  • 評論
  • 收藏
  • 共同學(xué)習(xí),寫下你的評論
感謝您的支持,我會繼續(xù)努力的~
掃碼打賞,你說多少就多少
贊賞金額會直接到老師賬戶
支付方式
打開微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊有機會得

100積分直接送

付費專欄免費學(xué)

大額優(yōu)惠券免費領(lǐng)

立即參與 放棄機會
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號

舉報

0/150
提交
取消