C # Indexer

Source: Internet
Author: User
An indexer allows an instance of a class or struct to be indexed in the same way as an array, with an indexer similar to an attribute, unlike an indexer whose access is a parameter.

Indexer and Array Comparisons:

(1) The indexer has an unrestricted index value (index) type

(2) Indexers allow overloading

(3) Indexer is not a variable

Different points of indexers and attributes

(1) Attributes are identified by name, and indexers are identified as functions

(2) indexers can be overloaded and properties cannot be

(3) The indexer cannot be declared static, and the property can

An example of a simple indexer

Using system;using System.collections;public class indexerclass{    private string[] name = new String[2];    The indexer must be defined with the This keyword, in fact this is the object after the class instantiation public    string This[int Index]    {        //Implement indexer Get method        get        {            if (Index < 2)            {                return name[index];            }            return null;        }        Implement the Set method of the indexer        set        {            if (Index < 2)            {                Name[index] = value            ;    }}} public class test{    static void Main ()    {        //indexer using        indexerclass Indexer = new Indexerclass ();        The "=" number to the right of the indexer assignment, is actually called its set method        indexer[0] = "Zhang San";       INDEXER[1] = "John Doe";        The value of the output indexer, in fact, is to call its Get method        Console.WriteLine (Indexer[0]);       Console.WriteLine (Indexer[1]);}    }

The indexer is accessed using a string as the subscript

public class indexerclass{    //when using string as indexer subscript, use Hashtable    private Hashtable name = new Hashtable ();    The indexer must be defined with the This keyword, in fact this is the object after the class instantiation 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"] = "Zhang San";        indexer["A0002"] = "John Doe";        Console.WriteLine (indexer["A0001"]);        Console.WriteLine (indexer["A0002"]);}    }

Overloading of indexers

public class indexerclass{Private Hashtable name = new Hashtable (); 1: Access the values public string This[int index] {get {return Name[index] via key. ToString (); } set {name. ADD (index, value); }}///2: Access key public int this[string AName] {get {//hashtable, diction is actually stored through the values                Aryentry (dictionary) type, if you want to traverse a hashtable, you need to use the 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 ();       The first type of indexer uses indexer[1] = "Zhang San";//set accessor is used indexer[2] = "John Doe";        Console.WriteLine ("Number 1 Name:" + indexer[1]),//get accessor is used Console.WriteLine ("Number 2 Name:" + indexer[2]); Console.wRiteline (); The second type of indexer uses Console.WriteLine ("Zhang San number is:" + indexer["Zhang San"]),//get accessor is used Console.WriteLine ("John Doe number is:" + indexer["       John Doe "]);    indexer["Harry"] = 3;//set accessor using Console.WriteLine ("Harry number is:" + indexer["Harry"]); }}

Multi-parameter indexer

Using system;using system.collections;//Entry Information Category public class entrantinfo{//Name, number, department 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;} }}//declares an indexer for a class Entrantinfo public class indexerforentrantinfo{private ArrayList arrlst;//for storing Entrantinfo class public index    Erforentrantinfo () {arrlst = new ArrayList (); }//Declare an indexer: Find Access department information by name and number public string this[string name, int num] {get {foreach (Ent Rantinfo en in Arrlst) {if (EN.name = = Name && en. num = = num) {return en.                Department;        }} return null; The set {//new keyword: C # Specifies that when you instantiate a class or call a class's constructor, you must use the new key Arrlst.add (The new Entrantinfo (name, num        , value)); }}//Declare an indexer: Find First name and department public ArrayList This[int Num] {get {ArrayList temp = new            ArrayList (); foreach (Entrantinfo en in Arrlst) {if (en. num = = num) {temp.                Add (en);        }} return temp; }}//can also declare multiple versions of indexers ...}        public class test{static void Main () {indexerforentrantinfo Info = new Indexerforentrantinfo ();        this[string name, int num] Use info["Zhang San", 101] = "Personnel Department";        info["John Doe", 102] = "Administrative department";        Console.WriteLine (info["Zhang San", 101]);        Console.WriteLine (info["John Doe", 102]);     Console.WriteLine ();   This[int num] uses foreach (Entrantinfo en in info[102]) {Console.WriteLine (en).            Name); Console.WriteLine (en.        Department); }    }}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.