VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > c#教程 >
  • C#教程之C#教程之C#索引器

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

索引器允许类或结构的实例就像数组一样进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。索引器经常是在主要用于封装内部集合或数组的类型中实现的。

索引器概述

  • 使用索引器可以用类似于数组的方式为对象建立索引;
  • get访问器返回值,set访问器分配值;
  • this关键字用于定义索引器;
  • 索引器不必根据整数值进行索引,可以自定义查找机制;
  • 索引器可被重载;
  • 索引器可以有多个行参;
  • 索引器必须是实例成员

简单示例

复制代码
public class Indexer<T>
    {
        private T[] _arr=new T[100];
        public T this[int i]
        {
            get { return _arr[i]; }
            set { _arr[i] = value; }
        }
    }
复制代码

简单示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Indexer<T>
   {
       string[] days = { "Sun""Mon""Tues""Wed""Thurs""Fri""Sat" };
 
       private int GetDay(string testDay)
       {
 
           for (int j = 0; j < days.Length; j++)
           {
               if (days[j] == testDay)
               {
                   return j;
               }
           }
           throw new System.ArgumentOutOfRangeException(testDay, "testDay must be in the form \"Sun\", \"Mon\", etc");
       }
 
       public int this[string day]
       {
           get
           {
               return (GetDay(day));
           }
       }
   }
相关教程