C# 进阶 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

索引器的定义

  索引器允许类或者结构的实例按照与数组相同的方式进行索引取值,索引器与属性类似,不同的是索引器的访问是带参的。声明与属性有些类似。索引器定义的时候不带有名称,但带有 this 关键字,它指向对象实例。语法如下:

  element-type this[type index] 
{
   // get 访问器
   get 
   {
      // 返回 index 指定的值
   }

   // set 访问器
   set 
   {
      // 设置 index 指定的值 
   }
}

其中: element-type 指元素类型, type 指索引的类型,可以是string、int等。

class DayCollection
{
    string[] days = { "Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat" };
    private int GetDay(string testDay)
    {
        for (int j = 0; j < days.Length; j++)
        {
            if (days[j] == testDay)
            {
                return j;
            }
        }
     }
     public int this[string day]  //索引器的定义,元素类型为int,索引类型为string
    {
        get                        //只有get属性,没有设置set属性
        {
            return (GetDay(day));
        }
    }
}