search
C# indexerDec 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]);
    }
}

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"]);
    }
}

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["王五"]);
    }
}

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);
        }
    }
}



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


Statement
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
How to use char array in C languageHow to use char array in C languageApr 03, 2025 pm 03:24 PM

The char array stores character sequences in C language and is declared as char array_name[size]. The access element is passed through the subscript operator, and the element ends with the null terminator '\0', which represents the end point of the string. The C language provides a variety of string manipulation functions, such as strlen(), strcpy(), strcat() and strcmp().

How to handle special characters in C languageHow to handle special characters in C languageApr 03, 2025 pm 03:18 PM

In C language, special characters are processed through escape sequences, such as: \n represents line breaks. \t means tab character. Use escape sequences or character constants to represent special characters, such as char c = '\n'. Note that the backslash needs to be escaped twice. Different platforms and compilers may have different escape sequences, please consult the documentation.

How to use various symbols in C languageHow to use various symbols in C languageApr 03, 2025 pm 04:48 PM

The usage methods of symbols in C language cover arithmetic, assignment, conditions, logic, bit operators, etc. Arithmetic operators are used for basic mathematical operations, assignment operators are used for assignment and addition, subtraction, multiplication and division assignment, condition operators are used for different operations according to conditions, logical operators are used for logical operations, bit operators are used for bit-level operations, and special constants are used to represent null pointers, end-of-file markers, and non-numeric values.

What is the role of char in C stringsWhat is the role of char in C stringsApr 03, 2025 pm 03:15 PM

In C, the char type is used in strings: 1. Store a single character; 2. Use an array to represent a string and end with a null terminator; 3. Operate through a string operation function; 4. Read or output a string from the keyboard.

The difference between multithreading and asynchronous c#The difference between multithreading and asynchronous c#Apr 03, 2025 pm 02:57 PM

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

How to convert char in C languageHow to convert char in C languageApr 03, 2025 pm 03:21 PM

In C language, char type conversion can be directly converted to another type by: casting: using casting characters. Automatic type conversion: When one type of data can accommodate another type of value, the compiler automatically converts it.

What is the function of C language sum?What is the function of C language sum?Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Avoid errors caused by default in C switch statementsAvoid errors caused by default in C switch statementsApr 03, 2025 pm 03:45 PM

A strategy to avoid errors caused by default in C switch statements: use enums instead of constants, limiting the value of the case statement to a valid member of the enum. Use fallthrough in the last case statement to let the program continue to execute the following code. For switch statements without fallthrough, always add a default statement for error handling or provide default behavior.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function