网站首页 > 技术教程 正文
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;
}
}
后面详细介绍索引器的类型
猜你喜欢
- 2024-11-08 NAS下搭建一个简洁的现代文件索引器,专注于您的文件。
- 2024-11-08 C# 中的性能提升 - Span 和 Memory
- 2024-11-08 Windows 10版本2004解决了重大Bug:再无高CPU占用和性能问题
- 2024-11-08 简析AVM白皮书:一种让BTC实现动态“状态机”的图灵完备虚拟机?
- 2024-11-08 自动化追剧系统的设置方法(自动化追剧系统的设置方法有哪些)
- 2024-11-08 微软确认:Win10 5月更新将大幅提升机械硬盘速度
- 2024-11-08 #好看电影推荐(#好看电影推荐大片9.0以上评分国产)
- 2024-11-08 105.C# 索引器Indexer(c中索引器的实现过程)
- 2024-11-08 有人知道枚举器和迭代器吗(枚举原理)
- 2024-11-08 nas-tools升级版更新,全新的功能和一些遇到的问题
你 发表评论:
欢迎- 最近发表
-
- Win11学院:如何在Windows 11上使用WSL安装Ubuntu
- linux移植(Linux移植freemodbus)
- 独家解读:Win10预览版9879为何无法识别硬盘
- 基于Linux系统的本地Yum源搭建与配置(ISO方式、RPM方式)
- Docker镜像瘦身(docker 减小镜像大小)
- 在linux上安装ollama(linux安装locale)
- 渗透测试系统Kali推出Docker镜像(kali linux渗透测试技术详解pdf)
- Linux环境中部署Harbor私有镜像仓库
- linux之间传文件命令之Rsync傻瓜式教程
- 解决ollama在linux中安装或升级时,通过国内镜像缩短安装时长
- 标签列表
-
- 下划线是什么 (87)
- 精美网站 (58)
- qq登录界面 (90)
- nginx 命令 (82)
- nginx .http (73)
- nginx lua (70)
- nginx 重定向 (68)
- Nginx超时 (65)
- nginx 监控 (57)
- odbc (59)
- rar密码破解工具 (62)
- annotation (71)
- 红黑树 (57)
- 智力题 (62)
- php空间申请 (61)
- 按键精灵 注册码 (69)
- 软件测试报告 (59)
- ntcreatefile (64)
- 闪动文字 (56)
- guid (66)
- abap (63)
- mpeg 2 (65)
- column (63)
- dreamweaver教程 (57)
- excel行列转换 (56)
本文暂时没有评论,来添加一个吧(●'◡'●)