zoukankan      html  css  js  c++  java
  • C#索引器的使用

    索引器这个东东,我也是最近才接触,一般所说的索引器,是指定义在某个类里面的一个类似属性的东西。索引器是.net中新的类成员。类似与类的属性。有些人干脆称呼它为带参数的属性。

    索引器可以快速定位到类中某一个数组成员的单元。下面看看代码:

    Indexer 
    class indexerClass
    {
    private int[] arr=new int[100];
    private string[] names=new string[100];
    public int this[int index]
    {
    get
    {
    if (index < 0 || index >= 100)
    {
    return -1;
    }
    else
    {
    return arr[index];
    }
    }
    set//索引器的get,set被编译器编译成get_item,sge_item方法。
    {
    if (index >=0 && index < 100)
    {
    arr[index]
    =value;
    }
    }
    }
    public int this[string key]//索引器的参数也可是字符串等,不一定只能是int
    {
    get
    {
    return GetNumber(key);
    }
    }
    public int GetNumber(string Gender)
    {
    if (Gender == "boy")
    {
    return 1;
    }
    else if (Gender == "girl")
    {
    return 0;
    }
    else
    {
    return -1;
    }
    }
    }

    索引器参数大多是int类型,但也可以是其他类型,如string。

    static void Main(string[] args)
    {
    indexerClass indexerTest
    = new indexerClass();
    for (int i = 0; i < 10; i++)
    {
    indexerTest[i]
    = i + 2; //对类的对象,可以直接像操作数组一样操作对象里面的数组。
    }
    for (int i = 0; i < 10; i++)
    {
    Console.WriteLine(indexerTest[i]);
    }
    Console.ReadKey();
    }
  • 相关阅读:
    PTA(Basic Level)1012.数字分类
    PTA(Basic Level)1011.A+B和C
    PTA(Basic Level)1008.数组元素循环右移问题
    PTA(Basic Level)1009.说反话
    PTA(Basic Level)1010.一元多项式求导
    Leetcode 38.报数 By Python
    Leetcode 35.搜索插入位置 By Python
    查看Linux的所有线程
    Linux内核模块编程——Hello World模块
    JSP内置对象总结
  • 原文地址:https://www.cnblogs.com/zhuawang/p/2155744.html
Copyright © 2011-2022 走看看