C# indexer

Dec 17, 2016 am 09:06 AM
Indexer

Indexers allow instances of classes or structures to be indexed in the same way as arrays. Indexers are similar to properties, except that indexer access takes parameters.

Comparison of indexers and arrays:

(1) The index value (Index) type of the indexer is not restricted

(2) The indexer allows overloading

(3) The indexer is not a variable

Indexer and The difference between attributes

(1) Attributes are identified by names, indexers are identified by functions

(2) Indexers can be overloaded, attributes cannot

(3) Indexers cannot be declared static, attributes can

A simple indexer example

using System;
using System.Collections;

public class IndexerClass
{
    private string[] name = new string[2];

    //索引器必须以this关键字定义,其实这个this就是类实例化之后的对象
    public string this[int index]
    {
        //实现索引器的get方法
        get
        {
            if (index < 2)
            {
                return name[index];
            }
            return null;
        }

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

Use string as subscript to access the indexer

public class IndexerClass
{
    //用string作为索引器下标的时候,要用Hashtable
    private Hashtable name = new Hashtable();

    //索引器必须以this关键字定义,其实这个this就是类实例化之后的对象
    public string this[string index]
    {
        get { return name[index].ToString(); 
        set { name.Add(index, value); }
    }
}
public class Test
{
    static void Main()
    {
        IndexerClass Indexer = new IndexerClass();
        Indexer["A0001"] = "张三";
        Indexer["A0002"] = "李四";
        Console.WriteLine(Indexer["A0001"]);
        Console.WriteLine(Indexer["A0002"]);
    }
}
Copy after login

Overloading of indexer

public class IndexerClass
{
    private Hashtable name = new Hashtable();

    //1:通过key存取Values
    public string this[int index]
    {
        get { return name[index].ToString(); }
        set { name.Add(index, value); }
    }

    //2:通过Values存取key
    public int this[string aName]
    {
        get
        {
            //Hashtable中实际存放的是DictionaryEntry(字典)类型,如果要遍历一个Hashtable,就需要使用到DictionaryEntry
            foreach(DictionaryEntry d in name)
            {
                if (d.Value.ToString() == aName)
                {
                    return Convert.ToInt32(d.Key);
                }
            }
            return -1;
        }
        set
        {
            name.Add(value, aName);
        }
    }
}
public class Test
{
    static void Main()
    {
        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["王五"]);
    }
}
Copy after login

Multi-parameter indexer

using System;
using System.Collections;

//入职信息类
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;
        }
    }

    //还可以声明多个版本的索引器...
}

public class Test
{
    static void Main()
    {
        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);
        }
    }
}
Copy after login



For more articles related to C# indexer, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the alternatives to NULL in C language What are the alternatives to NULL in C language Mar 03, 2025 pm 05:37 PM

This article explores the challenges of NULL pointer dereferences in C. It argues that the problem isn't NULL itself, but its misuse. The article details best practices for preventing dereferences, including pre-dereference checks, pointer initiali

How to add next-level C compiler How to add next-level C compiler Mar 03, 2025 pm 05:44 PM

This article explains how to create newline characters in C using the \n escape sequence within printf and puts functions. It details the functionality and provides code examples demonstrating its use for line breaks in output.

Which C language compiler is better? Which C language compiler is better? Mar 03, 2025 pm 05:39 PM

This article guides beginners on choosing a C compiler. It argues that GCC, due to its ease of use, wide availability, and extensive resources, is best for beginners. However, it also compares GCC, Clang, MSVC, and TCC, highlighting their differenc

Is NULL still important in modern programming in C language? Is NULL still important in modern programming in C language? Mar 03, 2025 pm 05:35 PM

This article emphasizes the continued importance of NULL in modern C programming. Despite advancements, NULL remains crucial for explicit pointer management, preventing segmentation faults by marking the absence of a valid memory address. Best prac

What are the web versions of C language compilers? What are the web versions of C language compilers? Mar 03, 2025 pm 05:42 PM

This article reviews online C compilers for beginners, focusing on ease of use and debugging capabilities. OnlineGDB and Repl.it are highlighted for their user-friendly interfaces and helpful debugging tools. Other options like Programiz and Compil

C language online programming website C language compiler official website summary C language online programming website C language compiler official website summary Mar 03, 2025 pm 05:41 PM

This article compares online C programming platforms, highlighting differences in features like debugging tools, IDE functionality, standard compliance, and memory/execution limits. It argues that the "best" platform depends on user needs,

Method of copying code by C language compiler Method of copying code by C language compiler Mar 03, 2025 pm 05:43 PM

This article discusses efficient code copying in C IDEs. It emphasizes that copying is an IDE function, not a compiler feature, and details strategies for improved efficiency, including using IDE selection tools, code folding, search/replace, templa

How to solve the problem of not popping up the output window by the C language compiler How to solve the problem of not popping up the output window by the C language compiler Mar 03, 2025 pm 05:40 PM

This article troubleshoots missing output windows in C program compilation. It examines causes like failing to run the executable, program errors, incorrect compiler settings, background processes, and rapid program termination. Solutions involve ch

See all articles