An in-depth understanding of the indexer and an in-depth understanding of the Index

Source: Internet
Author: User

An in-depth understanding of the indexer and an in-depth understanding of the Index

In our development, there are many common places where the indexer is used. The indexer is a very subtle member of a special class, which allows the object to be accessed in an array-like way, when a class contains arrays and set members, the indexer greatly simplifies access to arrays or set members. Make the program look more intuitive and easier to write.

I. Define the Indexer

The way to define the indexer is similar to the way to define attributes. The general form is as follows:

[Modifier] data type this [index type index]

{

Get {// code for obtaining attributes}

Set {// set the Property Code}

}

Modifiers includePublic, protected, private, internal, new, virtual, sealed, override, abstract, extern.

The data type is the type of the array or set element to be accessed.

The indexer type indicates which type of index the indexer uses to access arrays or set elements. It can be an integer or a string. this indicates operating the array or set members of this object, you can simply understand it as the name of the indexer. Therefore, the indexer cannot have a user-defined name.

II. The essence of the indexer is Class

3. Example of creating an index

 

Public class Person {// first defines an array private string [] str = new string [2]; // Add the indexer public string this [int index] {get {return str [index] ;}set {str [index] = value ;}}}

 

 

 

Call in the Main method

 

Person person = new Person (); // assign the person [0] = "Zhang San"; person [1] = "Li Si"; Console by means of the index. writeLine (person [0]); Console. writeLine (erson [1]); Console. readKey ();

 

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.