C#

面向对象(十三)-索引器

2017-12-10  本文已影响33人  元宇宙协会

1. 简介:

索引器允许类或结构的实例就像数组一样进行索引。 索引器类似于属性,不同之处在于它们的取值函数采用参数。 典型用法 数组中[]

2. 语法:

关键字符:this[]

    class IndexTest
    {
        private int[] arrayInts = new[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        
        public int this[int index]
        {
            get { return arrayInts[index]; }
            set { arrayInts[index] = value; }
        }
    }

    // 使用该类
    class Program
    {
        static void Main(string[] args)
        {
            IndexTest test = new IndexTest();
            Console.WriteLine(test[5]); // 6
            Console.ReadKey();
        }
    }

3. 索引器概述:

4. 索引器其他用法:

       public int this[int index1,int index2]
        {
            get
            {
                if (index1 > MyInt1.Length)
                {
                    throw new Exception("超出异常");
                }
                else
                {
                    return MyInt1[index1,index2];
                }
            }
            set {
                MyInt1[index1,index2] = value;
            }            
        }    

        // 调用:
        static void Main(string[] args)
        {
            IndexTest test = new IndexTest();
            Console.WriteLine(test[12,6]); 
            Console.ReadKey();
        }

案例说明:在此例中,声明了存储星期几的类。 声明了一个 get
访问器,它接受字符串(天名称),并返回相应的整数。 例如,星期日将返回 0,星期一将返回 1,等等。

        class DayCollection
        {
            string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };

            // This method finds the day or returns -1
            private int GetDay(string testDay)
            {

                for (int j = 0; j < days.Length; j++)
                {
                    if (days[j] == testDay)
                    {
                        return j;
                    }
                }

                throw new System.ArgumentOutOfRangeException(testDay, "testDay must be in the form \"Sun\", \"Mon\", etc");
            }

            // The get accessor returns an integer for a given string
            public int this[string day]
            {
                get
                {
                    return (GetDay(day));
                }
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                DayCollection week = new DayCollection();
                System.Console.WriteLine(week["Fri"]);

                // Raises ArgumentOutOfRangeException
                System.Console.WriteLine(week["Made-up Day"]);

                // Keep the console window open in debug mode.
                System.Console.WriteLine("Press any key to exit.");
                System.Console.ReadKey();
            }
        }
        // Output: 5

作者:silence_k
链接:http://www.jianshu.com/p/44806f324193
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

上一篇 下一篇

猜你喜欢

热点阅读