c#教程——索引器

前言:

索引器(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);

        }
    }

结果:

相关推荐
MM_MS6 小时前
Halcon图像点运算、获取直方图、直方图均衡化
图像处理·人工智能·算法·目标检测·计算机视觉·c#·视觉检测
会开花的二叉树7 小时前
吃透Reactor多线程:EventLoop_Channel_ThreadPool协作原理
开发语言·c++·tcp/ip·servlet
老骥伏枥~7 小时前
C# 控制台:Console.ReadLine / WriteLine
开发语言·c#
PfCoder19 小时前
C#中定时器之System.Timers.Timer
c#·.net·visual studio·winform
人工智能AI技术1 天前
【C#程序员入门AI】本地大模型落地:用Ollama+C#在本地运行Llama 3/Phi-3,无需云端
人工智能·c#
Hx_Ma161 天前
SpringMVC返回值
java·开发语言·servlet
MyBFuture1 天前
C#数组详解:一维二维与交错数组
开发语言·windows·c#·visual studio·vision pro
有来技术1 天前
ASP.NET Core 权限管理系统(RBAC)设计与实现|vue3-element-admin .NET 后端
vue.js·后端·c#·asp.net·.net
张人玉1 天前
C#WinFrom中show和ShowDialog的区别
开发语言·microsoft·c#