前言:
索引器(Indexer)可以像操作数组一样来访问对象的元素。它允许你使用索引来访问对象中的元素,就像使用数组索引一样。在C#中,索引器的定义方式类似于属性,但具有类似数组的访问方式。
索引器:
            
            
              cs
              
              
            
          
          public returnType this[indexType index] {
    // 索引器的 get 访问器
    get {
        // 返回与索引相关的值
    }
    // 索引器的 set 访问器
    set {
        // 设置与索引相关的值
    }
}
        returnType是索引器返回的值的类型。indexType是索引的类型。this[index]是索引器的声明,其中index是索引参数。get访问器用于获取与指定索引相关的值。set访问器用于设置与指定索引相关的值。
假设有一个名为MyCollection的类,可以通过类似myCollection[0]的方式来访问其中的元素。这时候就可以使用索引器。在MyCollection类中定义一个索引器,可以使用整数索引来访问其中的元素。代码中体会更容易理解
创建一个项目,创建一个MyCollection类
            
            
              cs
              
              
            
          
          using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 索引器
{
    internal class MyCollection
    {
        private string[] elements = new string[3] { "1","2","3"}; // 创建1~3字符串的数组
        // 索引器定义
        public string this[int index]
        {
            get
            {
                // 在获取元素时,返回对应索引的元素
                return elements[index];
            }
            set
            {
                // 在设置元素时,将值赋给对应索引的元素
                elements[index] = value;
            }
        }
    }
}
        program类:
            
            
              cs
              
              
            
          
          namespace 索引器
{
    internal class Program
    {
        static void Main(string[] args)
        {
            MyCollection collection = new MyCollection();
            // 修改第一个元素的值
            collection[0] = "Element 1";
     
            // 获取第一、二个元素的值
            string element1 = collection[0];
            string element2 = collection[1];
            // 打印第一、二个元素的值
            Console.WriteLine("第一个元素的值是:" + element1);
            Console.WriteLine("第二个元素的值是:" + element2);
        }
    }
        结果:
