当前位置: 首页 > news >正文

C#—索引器

C#—索引器

索引器(Indexer)是类中的一个特殊成员,它能够让对象以类似数组的形式来操作,使程序看起来更为直观,更容易编写。索引器与属性类似,在定义索引器时同样会用到 get 和 set 访问器,不同的是,访问属性不需要提供参数而访问索引器则需要提供相应的参数。

文章借鉴于:  C#教程(非常详细) - C语言中文网

主要特点:

语法:索引器使用 this 关键字。
可访问性:可以使用不同的访问修饰符(如 public、private 等)。
类型:索引器可以接受多个参数并返回任意数据类型。
重载:可以为同一类定义多个索引器,使其能够根据不同的参数来访问不同类型的数据。

定义索引器

C# 中属性的定义需要提供属性名称,而索引器则不需要具体名称,而是使用 this 关键字来定义,语法格式如下:

索引器类型 this[int index]
{
    // get 访问器
    get
    {   
        // 返回 index 指定的值
    }

    // set 访问器
    set
    {
        // 设置 index 指定的值
    }
}

示例:

internal class Program
{static void Main(string[] args){Employee e = new Employee();e[17] = "迪迦";e[18] = "赛罗";Console.WriteLine(e[17]);Console.ReadKey();}class Employee{public Dictionary<int, string> dic = new Dictionary<int, string>(); // 存储姓名和年龄public string this[int index] // 索引器属性{get { return dic[index]; }set { dic[index] = value; }}}
}

结果:

迪迦

索引器重载:

class Demo{static void Main(string[] args){Demo names = new Demo();names[0] = "C#";names[1] = "索引器";// 使用带有 int 参数的第一个索引器for (int i = 0; i < Demo.size; i++){Console.WriteLine(names[i]);}// 使用带有 string 参数的第二个索引器Console.WriteLine("“C#”的索引为:{0}",names["C#"]);Console.ReadKey();}static public int size = 10;private string[] namelist = new string[size];public Demo(){for (int i = 0; i < size; i++)namelist[i] = "NULL";}public string this[int index]{get{string tmp;if( index >= 0 && index <= size-1 ){tmp = namelist[index];}else{tmp = "";}return ( tmp );}set{if( index >= 0 && index <= size-1 ){namelist[index] = value;}}}public int this[string name]{get{int index = 0;while(index < size){if(namelist[index] == name){return index;}index++;}return index;}}}

结果:

C#
索引器
NULL
NULL
NULL
NULL
NULL
NULL

NULL
NULL
“C#”的索引为:0

http://www.lryc.cn/news/504338.html

相关文章:

  • 杨振宁大学物理视频中黄色的字去掉(稳定简洁版本,四)
  • 排序算法(5):归并排序
  • Gate学习(7)引入体素源
  • 2024.12.14 TCP/IP 网络模型有哪几层?
  • item2 for macos
  • 二维三维空间上两点之间的距离
  • 相机测距原理
  • Debezium SchemaNameAdjuster 分析
  • Stable Diffusion绘画 | SDXL模型使用注意事项
  • (五)机器学习 - 数据分布
  • Flink State面试题和参考答案-(上)
  • 利用开源Stable Diffusion模型实现图像压缩比竞争方法用更低的比特率生成更逼真的图像
  • QT信号与槽机制详解
  • openGauss开源数据库实战二十二
  • BurpSuite解决暴力破解时需要验证码问题
  • WPF Combox使用 Text无法选择正确获取CHange后的Text
  • 【速览】设计模式(更新中)
  • 【stable diffusion部署】Stable Diffusion开源本地化的文生图图生图AI
  • 县城楼市踩踏式降价,或现2字头,率先回归月薪一平方的合理价格
  • 计算机组成原理(七):二进制编码
  • 【GitHub分享】you-get项目
  • 论文概览 |《Sustainable Cities and Society》2024.12 Vol.116
  • 解决node.js的req.body为空的问题
  • Mysql学习笔记之安装
  • 将PDF流使用 canvas 绘制然后转为图片展示在页面上(二)
  • 【深度学习】 零基础介绍卷积神经网络(CNN)
  • Coze概述
  • 康佳Android面试题及参考答案(多张原理图)
  • 2022 年 3 月青少年软编等考 C 语言四级真题解析
  • 关于24年408真题的疑问