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);

        }
    }

结果:

相关推荐
o0向阳而生0o2 小时前
28、.NET 中元数据是什么?
microsoft·c#·.net
niuTaylor3 小时前
Linux驱动开发快速上手指南:从理论到实战
linux·运维·开发语言·驱动开发·c#
军训猫猫头4 小时前
89.WPF 中实现便捷的数字输入框:DecimalUpDown 控件的使用 WPF例子 C#例子.
开发语言·c#·wpf
冰茶_5 小时前
.NET MAUI 发展历程:从 Xamarin 到现代跨平台应用开发框架
学习·microsoft·微软·c#·.net·xamarin
The Future is mine7 小时前
C# new Bitmap(32043, 32043, PixelFormat.Format32bppArgb)报错:参数无效,如何将图像分块化处理?
开发语言·c#
人生导师yxc14 小时前
Servlet小结
servlet
Iotfsd14 小时前
.NET写的开源工业物联网网关(IoTGateway)
物联网·c#·.net·dotnet·边缘网关·雾计算·工业物联网智能网关
先生沉默先14 小时前
c#接口_抽象类_多态学习
开发语言·学习·c#
江沉晚呤时14 小时前
深入了解C# List集合及两种常见排序算法:插入排序与堆排序
windows·sql·算法·oracle·c#·排序算法·mybatis
iReachers15 小时前
使用命令行加密混淆C#程序
开发语言·c#