首页 > 技术文章 > 索引器

T-ARF 2018-10-09 03:13 原文

索引器是一个非常快速查找,赋值的一个方法。

建立一个索引器是一个简单的过程。

索引器和属性有同样的get和set。用法也是一样的

不过在索引器的建立的时候,要注意必须要返回值和this关键字【对应着实例化的类】

索引器不限制重载

索引器不限参数数量

索引器不限制返回值类型但必须有

  public class TestIndex
    {
        private int [] id;        
        public TestIndex(int n) => id = new int[n]; 
        public int this[int index]
        {       
            get
            {
                if (index <= id.Length)
                    return id[index];
                return int.MinValue;
            }
            set
            {
                if (index < id.Length)
                    id[index] = value;
            }          
        }
        public int [] this[int from,int to]
        {
            get
            {
                int[] reulst=null;
                if (from < id.Length && from >= 0 && to < id.Length && to >= 0)
                {
                    if (from == to)
                        return new int[] { id[from] };

                    reulst = new int[to - from];

                    while (from < to)
                    {
                        reulst[from] = id[from];
                        from++;
                    }
                }
                return reulst;
            }
        }
    }
    class Program

测试

  class Program
    {
        static void Main(string[] args)
        {
            var test = new TestIndex(5);
            test[0] = 10;
            test[1] = 20;
            test[2] = 30;
            var ten = test[0];
            Console.WriteLine(ten);
            //输出10
            var array = test[0, 2];
            foreach (var item in array)
                Console.WriteLine($"{item}");
            //输出10 20 
        }
    }

 

推荐阅读