zoukankan      html  css  js  c++  java
  • 【c# 学习笔记】索引器

      当一个类包含数组成员时,索引器 的使用将大大地简化对类中数组成员的访问。索引器的定义类似于属性,也具有GET访问器和set访问器,如下:

      

        [修饰符] 数据类型 this[索引类型 index]
        {
            get { //返回类中数组某个元素}
            set { //对类中数组元素赋值}
        }

      其中,数据类型是类中药存取的数组的类型;索引类型表示该索引器使用哪一个类型的索引来存取数组元素,可以是整型,也可以是字符串类型;

    this则表示所操作的是类对象的数组成员,可以简单地把它理解为索引器的名字(注意,索引器不能自定义名称)。如下:

      

        class Person
        {
            //可容纳10个整数的整数数组
            private int[] intarray = new int[10];
    
            //索引器的定义
    
            public int this[int index]
            {
                get
                {
                    return intarray[index];
                }
    
                set
                {
                    intarray[index] = value;
                }
            }
     
        }

      使用如下:

            static void Main(string[] args)
            {
    
    
                Person person = new Person();
    
                person[0] = 1;
                person[1] = 2;
                person[2] = 3;
    
                Console.WriteLine(person[0]);
                Console.WriteLine(person[1]);
                Console.WriteLine(person[2]);
    
                Console.Read();
            }
  • 相关阅读:
    「考试」省选27
    「考试」省选26
    「考试」省选25
    $dy$讲课总结
    「笔记」$Min\_25$筛
    「考试」省选24
    「总结」多项式生成函数例题(4)
    「总结」多项式生成函数相关(4)
    「考试」省选23
    「总结」后缀3
  • 原文地址:https://www.cnblogs.com/xiaoyehack/p/9204741.html
Copyright © 2011-2022 走看看