Using the indexer (C # programming guide)

Source: Internet
Author: User
C # programming guide Using the indexer (C # programming guide)

The indexer allows you to index classes, structures, or interfaces by processing arrays. For more information about using the indexer for an interface, see interface indexer.

To declare the class or structure indexer, use the this keyword, as shown in the following example:

Copy code
 
Public int this [int Index] // indexer declaration {// get and set accessors}
Remarks

The index type and its parameter types must be at least as accessible as the index itself. For more information on accessible levels, see access modifiers.

The signature of the indexer consists of the number and type of its form parameters. It does not include the index type or parameter name. If more than one indexer is declared in the same category, they must have different signatures.

The index value is not classified as a variable. Therefore, you cannot pass the index value as a ref or out parameter.

To provide the indexer with a name that can be used in other languages, useNameAttribute. For example:

Copy code
[System. runtime. compilerservices. indexername ("theitem")] public int this [int Index] // indexer declaration {}

This indexer will have a nameTheitem. If the name attribute is not provided, it will be generatedItemDefault name.

Example 1

The following example shows how to declare a private array field,ArrAnd indexer. You can use the indexer to directly access the instance.Test [I]. Another way to use the indexer is to declare the array as a Public Member and directly access its members.Arr [I].

C # copy code
 Class Indexerclass { Private   Int [] Arr = New   Int [100]; Public   Int   This [Int Index] // Indexer Declaration { Get { // Check the index limits.  If (Index <0 | index> = 100 ){ Return 0 ;} Else { Return Arr [Index] ;}} Set { If (! (Index <0 | index> = 100) {arr [Index] = value ;}}}} Class Mainclass { Static   Void Main () {indexerclass test = New Indexerclass (); // Call the indexer to initialize the elements #3 and #5. Test [3] = 256; test [5] = 1024; For ( Int I = 0; I <= 10; I ++) {system. Console. writeline ( "Element # {0} = {1 }" , I, test [I]) ;}}

Output

Element #0 = 0

Element #1 = 0

Element #2 = 0

Element #3 = 256

Element #4 = 0

Element #5 = 1024

Element #6 = 0

Element #7 = 0

Element #8 = 0

Element #9 = 0

Element #10 = 0

Note that when accessing the indexer (for exampleConsole. WriteThe get accessors are called. Therefore, ifGetIf the accessor does not exist, a compilation error will occur.

Index with other values

C # does not limit the index type to an integer. For example, it may be useful for the indexer to use strings. This type of Indexer can be implemented by searching strings in a set and returning corresponding values. Because the accessors can be overloaded, the string and integer versions can coexist.

Example 2

In this example, the class for storing the day of the week is declared. DeclaredGetAccessors. It accepts the string (day name) and returns an integer. For example, 0 is returned for Sunday, 1 is returned for Monday, and so on.

C # copy code
 // Using a string as an indexer Value  Class Daycollection { String [] Days = { "Sun" , "Mon" , "Tues" ,"Wed" , "Thurs" , "Fri" , "Sat" }; // This method finds the day or returns-1  Private   Int Getday ( String Testday ){ Int I = 0; Foreach ( String Day In Days ){ If (Day = testday ){Return I;} I ++ ;} Return -1 ;} // The get accessor returns an integer for a given string  Public   Int   This [ String Day] { Get { Return (Getday (day ));}}} Class Program { Static   Void Main ( String [] ARGs) {daycollection week = New Daycollection (); system. Console. writeline (week [ "Fri" ]); System. Console. writeline (week [ "Made-up day" ]) ;}}

Output

5

-1

Reliable Programming

There are two main ways to improve the security and reliability of the indexer:

    • Always ensure that yourCodeCheck the execution scope and type.

    • Should beGetAnd set accessors with as many access restrictions as possible. This is trueSetThe accessors are particularly important. For more information, see asymmetric accessors (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.