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

(二)CSharp-索引器

1、索引器定义

什么是索引器

  • 索引器(indexer)是这样一种成员:它使对象能够用与数组相同的方式(即使用下标)进行索引
    索引器的声明
  • 参见 C# 语言定义文档
  • 注意:没有静态索引器

索引器是一组 get 和 set 访问器,与属性类似:

  • 和属性一样,索引器不用分配内存来存储
  • 索引器和属性都主要来访问其他数据成员,它们与这些成员关联,并为它们提供获取和设置访问。
  • 属性通常表示单个数据成员
  • 索引器通常表示多个数据成员

注意:

  • 索引器总是实例成员,因此不能被声明为 static。

索引器的特点:

  • 索引器的索引值(Index)类型不受限制
  • 索引器允许重载
  • 索引器不是一个变量

请添加图片描述

2、索引器代码例子

(1)代码例子:采用字典方式

 class Program{static void Main(string[] args){Student stu = new Student();stu["Math"] = 90;var mathScore = stu["Math"];Console.WriteLine(mathScore);}}class Student{private int age;public int Age{get { return age; }set { age = value; }}private Dictionary<string, int> scoreDictionary = new Dictionary<string, int>();public int? this[string subject]{get{if(this.scoreDictionary.ContainsKey(subject)){return this.scoreDictionary[subject];}else{return null;}}set{if (value.HasValue == false){throw new Exception("Score cannot be null.");}if(this.scoreDictionary.ContainsKey(subject)){this.scoreDictionary[subject] = value.Value;//value 为可空类型}else{this.scoreDictionary.Add(subject, value.Value);}}}}

(2)代码例子:采用索引值方式
以下所有例子都来源于:# 索引器的多个例子及重载

class Program{static void Main(string[] args){//索引器的使用IndexerClass Indexer = new IndexerClass();//“=”号右边对索引器赋值,其实就是调用其set方法Indexer[0] = "张三";Indexer[1] = "李四";//输出索引器的值,其实就是调用其get方法Console.WriteLine(Indexer[0]);Console.WriteLine(Indexer[1]);Console.ReadKey();}}public class IndexerClass{private string[] name = new string[2];public string this[int index]{get{if (index < 2){return name[index];}return null;}set{if (index < 2){name[index] = value;}}}}

(3)代码例子:采用字符串为下标方式

    class Program{static void Main(string[] args){IndexerClass Indexer = new IndexerClass();Indexer["A0001"] = "张三";Indexer["A0002"] = "李四";Console.WriteLine(Indexer["A0001"]);Console.WriteLine(Indexer["A0002"]);Console.ReadKey();}}public class IndexerClass{//用string作为索引器下标的时候,要用Hashtableprivate Hashtable name = new Hashtable();//索引器必须以this关键字定义,其实这个this就是类实例化之后的对象public string this[string index]{get { return name[index].ToString(); }set { name.Add(index, value); }}}

3、索引器重载

 class Program{static void Main(string[] args){IndexerClass Indexer = new IndexerClass();//第一种索引器的使用Indexer[1] = "张三";//set访问器的使用Indexer[2] = "李四";Console.WriteLine("编号为1的名字:" + Indexer[1]);//get访问器的使用Console.WriteLine("编号为2的名字:" + Indexer[2]);Console.WriteLine();//第二种索引器的使用Console.WriteLine("张三的编号是:" + Indexer["张三"]);//get访问器的使用Console.WriteLine("李四的编号是:" + Indexer["李四"]);Indexer["王五"] = 3;//set访问器的使用Console.WriteLine("王五的编号是:" + Indexer["王五"]);Console.ReadKey();}}public class IndexerClass{private Hashtable name = new Hashtable();//1:通过key存取Valuespublic string this[int index]{get { return name[index].ToString(); }set { name.Add(index, value); }}//2:通过Values存取keypublic int this[string aName]{get{//Hashtable中实际存放的是DictionaryEntry(字典)类型,如果要遍历一个Hashtable,就需要使用到DictionaryEntryforeach (DictionaryEntry d in name){if (d.Value.ToString() == aName){return Convert.ToInt32(d.Key);}}return -1;}set{name.Add(value, aName);}}}

4、多参索引器

   //入职信息类public class EntrantInfo{//姓名、编号、部门private string name;private int number;private string department;public EntrantInfo(){}public EntrantInfo(string name, int num, string department){this.name = name;this.number = num;this.department = department;}public string Name{get { return name; }set { name = value; }}public int Num{get { return number; }set { number = value; }}public string Department{get { return department; }set { department = value; }}}//声明一个类EntrantInfo的索引器public class IndexerForEntrantInfo{private ArrayList ArrLst;//用于存放EntrantInfo类public IndexerForEntrantInfo(){ArrLst = new ArrayList();}//声明一个索引器:以名字和编号查找存取部门信息public string this[string name, int num]{get{foreach (EntrantInfo en in ArrLst){if (en.Name == name && en.Num == num){return en.Department;}}return null;}set{//new关键字:C#规定,实例化一个类或者调用类的构造函数时,必须使用new关键ArrLst.Add(new EntrantInfo(name, num, value));}}//声明一个索引器:以编号查找名字和部门public ArrayList this[int num]{get{ArrayList temp = new ArrayList();foreach (EntrantInfo en in ArrLst){if (en.Num == num){temp.Add(en);}}return temp;}}//还可以声明多个版本的索引器...}class Program{static void Main(string[] args){IndexerForEntrantInfo Info = new IndexerForEntrantInfo();//this[string name, int num]的使用Info["张三", 101] = "人事部";Info["李四", 102] = "行政部";Console.WriteLine(Info["张三", 101]);Console.WriteLine(Info["李四", 102]);Console.WriteLine();//this[int num]的使用foreach (EntrantInfo en in Info[102]){Console.WriteLine(en.Name);Console.WriteLine(en.Department);}Console.ReadKey();}}
http://www.lryc.cn/news/92611.html

相关文章:

  • 配合AI刷leetcode 实现1170
  • English Learning - L3 作业打卡 Lesson5 Day36 2023.6.9 周五
  • 前端框架笔记
  • 详细设计文档
  • Java011——Java数据类型转换(基本数据类型)
  • mybatis-plus用法(二)
  • SQL笔记-存储过程+循环
  • HNU-操作系统OS-作业1(4-9章)
  • springboot 精华
  • 我用ChatGPT写2023高考语文作文(三):新课标I卷
  • HTML 标签的学习
  • 计算耗时为微秒的方法(包含:时/分/秒/毫秒/微秒/纳秒)
  • 通过 Python 封装关键词搜索阿里巴巴商品api接口
  • 分布式光伏消纳的微电网群共享储能配置策略研究(Matlab代码实现)
  • C语言写网络爬虫总体思路
  • 机器学习实战六步法之训练模型、优化模型、部署模型(七)
  • 《C++高级编程》读书笔记(七:内存管理)
  • Scrum团队的三个角色
  • python环境中使用 requirement.txt 安装依赖
  • UE5 材质常用大全
  • 笔记本安装centos操作系统
  • Polarion工作流插件(自定义)
  • JavaScript库:jQuery,简化编程
  • [springboot]菜鸟学习- JdbcTemplate用法浅尝
  • 11.无监督学习之主成分分析
  • 「HTML和CSS入门指南」figcaption 标签详解
  • 电子企业实施数字化工厂建设之前,需要注意哪些
  • 迅捷pdf实现多页插入
  • 调用阿里云API实现证件照生成
  • PHP 转换 excel中读取的时间