编程技术分享平台

网站首页 > 技术教程 正文

索引器(Indexer)(12-1)-C#编程零基础到入门学习

xnh888 2024-11-08 14:46:15 技术教程 63 ℃ 0 评论

C#中的索引器(Indexer),是用于访问和操作集合类型(如数组、列表、字典等)中元素的特殊成员。它使用类似于数组下标的方式,提供了一种简单而直观的方式来访问和修改集合中的元素。

索引器是一种特殊的属性,它允许像访问其内部集合的数组一样访问类或结构。C#允许自定义索引器,通用索引器以及重载索引器。

可以使用带有 this 关键字和方括号 [ ] 的属性来定义索引器。

语法

<return type> this[<parameter type> index]
{ 
   get{
        // 从内部集合的指定索引返回值
    }
   set{ 
       // 在内部集合中的指定索引处设置值
    }
}

定义索引器

public class MyCollection<T>  
{  
    private T[] arr;  
  
    public T this[int index]  
    {  
        get  
        {  
            return arr[index];  
        }  
        set  
        {  
            arr[index] = value;  
        }  
    }  
}

完整示例代码:

创建一个MyCollection<int>的实例,并使用索引器来添加、访问和修改元素。

using System;
using System.Collections;
using System.Text;
using System.Threading.Tasks;

namespace IndexerUse
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 创建 MyCollection<int> 实例  
            MyCollection<int> collection = new MyCollection<int>();

            // 向集合添加元素  
            collection[0] = 1;
            collection[1] = 2;
            collection[2] = 3;
            collection[3] = 4;
            // 使用索引器访问元素  
            Console.WriteLine(collection[0]);  // 输出:10  
            Console.WriteLine(collection[1]);  // 输出:20  
            Console.WriteLine(collection[2]);  // 输出:30  

            // 修改元素  
            collection[0] = 100;
            Console.WriteLine(collection[0]);  // 输出:100  
        }
    }
    public class MyCollection<T>
    {
        private T[] arr;

        public MyCollection()
        {
            arr = new T[10];  // 初始化一个大小为10的数组  
        }

        public T this[int index]
        {
            get
            {
                return arr[index];
            }
            set
            {
                arr[index] = value;
            }
        }
    }
}

从 C# 7开始,可以对 get 和 set 使用表达式体语法。

class StringDataStore
{
    private string[] strArr = new string[10]; // 内部数据存储

    public string this[int index]
    {
        get => strArr[index];

        set => strArr[index] = value;
    }
}

后面详细介绍索引器的类型

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表