C#之索引Index和范围Range的使用。

简单介绍下索引和范围的简单使用。
比如我们想获得数组中的倒数第一个元素。我们可以通过C#内置函数^1进行快速定位。返回倒数第二个元素就直接^2以此类推。
具体如下:

    string[] words = new string[]
        {
            "one",
            "tow",
            "three",
            "four",
            "five"
        };

        public string GetLastOne()
        {
            Index index = ^1; //返回最后一个元素
            //或者直接words[^1]
            return words[index];
        }

假如你想返回前3个元素。那么可以使用Range,比如0..3

   public string[] GetRanges()
        {
            //Range a = 0..3;
           // var strs = words[a];
            return words[0..3];
        }

索引的简单定义:如类索引。

   public string  this[int index]
            {
            get {
                return words[index];
            } set 
            {
                words[index] = value;
            }
            }

索引重载

  //重载索引
           public int this[string str] 
        {
            get {
                return Array.IndexOf(words, str);
            }
           
        } 

最后给出整体代码和运行结果:

using System;

namespace IndexAndRange
{
    class Program
    {
        static void Main(string[] args)
        {
            Point p = new Point();
            Console.WriteLine("获取最后一个");
            string laststr = p.GetLastOne();
            Console.WriteLine(laststr);

            Console.WriteLine("获取范围0-3的值");
            foreach (var item in p.GetRanges())
            {
                Console.WriteLine(item);
            }

            Console.WriteLine("获取类索引值");
            Console.WriteLine(p[0]);
            Console.WriteLine("为索引赋值");
            p[0] = "six";
            Console.WriteLine(p[0]);
            Console.WriteLine("获取位置信息");
            Console.WriteLine(p["six"]);

            Console.ReadLine();


        }
    }



    public class Point
    {

        string[] words = new string[]
        {
            "one",
            "tow",
            "three",
            "four",
            "five"
        };

        public string GetLastOne()
        {
            Index index = ^1;
            return words[index];
        }

        public string[] GetRanges()
        {
            Range a = 0..3;
            var strs = words[a];
            return words[0..3];
        }

     
    
            public string  this[int index]
            {
            get {
                return words[index];
            } set 
            {
                words[index] = value;
            }
            }


        //重载索引
           public int this[string str] 
        {
            get {
                return Array.IndexOf(words, str);
            }
           
        } 


    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值