c#教程——索引器

前言:

索引器(Indexer)可以像操作数组一样来访问对象的元素。它允许你使用索引来访问对象中的元素,就像使用数组索引一样。在C#中,索引器的定义方式类似于属性,但具有类似数组的访问方式。

索引器:

public returnType this[indexType index] {
    // 索引器的 get 访问器
    get {
        // 返回与索引相关的值
    }
    // 索引器的 set 访问器
    set {
        // 设置与索引相关的值
    }
}
  • returnType 是索引器返回的值的类型。
  • indexType 是索引的类型。
  • this[index] 是索引器的声明,其中 index 是索引参数。
  • get 访问器用于获取与指定索引相关的值。
  • set 访问器用于设置与指定索引相关的值。

假设有一个名为MyCollection的类,可以通过类似myCollection[0]的方式来访问其中的元素。这时候就可以使用索引器。在MyCollection类中定义一个索引器,可以使用整数索引来访问其中的元素。代码中体会更容易理解

创建一个项目,创建一个MyCollection类

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类:

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

        }
    }

 结果:

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值