Indexers (C # Programming Guide)

Source: Internet
Author: User

Original address: Https://msdn.microsoft.com/zh-cn/library/6x16t2tx (vs.80). aspx

Indexers allow instances of a class or struct to be indexed in the same way as an array. Indexers are similar to properties, except that their accessors take parameters.

In the following example, a generic class is defined and a simple get and set accessor method (as a method of assigning and retrieving values) is provided. The program class creates an instance of this class for the storage string.

C#
Class samplecollection<t>{    private t[] arr = new t[100];    Public T This[int i]    {        get        {            return arr[i];        }        Set        {            Arr[i] = value;}}    } This class shows how client code uses the Indexerclass program{    static void Main (string[] args)    {        Sample collection<string> stringcollection = new samplecollection<string> ();        Stringcollection[0] = "Hello, world";        System.Console.WriteLine (Stringcollection[0]);}    }
Indexer Overview
    • Indexers enable an object to be indexed in a similar way to an array.

    • The get accessor returns a value. The set accessor assigns a value.

    • The This keyword is used to define indexers.

    • The value keyword is used to define the values assigned by the set indexer.

    • Indexers do not have to be indexed by integer values, and you decide how to define a specific lookup mechanism.

    • Indexers can be overloaded.

    • Indexers can have multiple parameters, such as when accessing a two-dimensional array.

related chapters
    • Using Indexers (C # Programming Guide)

    • Indexers in Interfaces (C # Programming Guide)

    • Comparisons between properties and indexers (C # Programming Guide)

    • Asymmetric accessor Accessibility (C # Programming Guide)

    • Indexer Sample

    • Index Properties sample

Indexers (C # Programming Guide)

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.