C # Indexer

Source: Internet
Author: User

Introduction: we often see such classes: Aclass A = new class ();ProgramA [I] = "some string"; it feels strange:Since the class array is not declared, it uses [] indexes and returns a string type,

Indexer Overview: To put it simply, the C # indexer is a special type of attribute. With these attributes, You can reference your own classes as you reference arrays.

The indexer allows objects to be indexed in a way similar to an array.

Get accessors return values. Set accessors allocation value.

This keyword is used to define the indexer.

The value keyword is used to define the value allocated by the set indexer.

The indexer does not need to index based on the integer value. It is up to you to decide how to define a specific search mechanism.

The indexer can be overloaded.

The indexer can have multiple parameters, for example, when accessing a two-dimensional array.

C # the most interesting part of the language is the class indexer ). To put it simply, the so-called indexer is a special type of attributes. With these attributes, You can reference your own classes as you reference arrays. Obviously, this function is particularly useful when creating collection classes. In some other cases, such as processing large files or abstracting some limited resources, it is of course very useful to make classes behave like arrays.

 

Like the method, the indexer has five access protection levels, four inheritance behavior modifiers, and an external indexer. There is no difference between these actions and the method. I will not repeat them here.The only difference is that the indexer cannot be static), Which is easy to understand in the semantics of object reference. It is worth noting that base [e] should be used to access the parent class indexer when override is used to implement the indexer.

 

Same as attribute implementation,The data type of The indexer is both the return type of the get statement block and the type of the value keyword in the Set statement block..

The parameter list of The indexer is also worth noting.. The "Index" feature requires the index to have at least one parameter, which is placed in brackets after the this keyword. The parameters of the indexer can only be of the value type. They cannot be modified by REF (reference) or out (output. The data type of the parameter can be any data type in C. C # perform Polymorphism Analysis On The indexer based on different parameter signatures. All parameters in brackets can be referenced under get and set, while the value keyword can only be used as a passing parameter under set.

The indexer is usually used to provide a friendly access interface for the objects in the object container-that is why C # wraps the method into an indexer. In fact, we can see that the indexer has a large number of applications in the. NET Framework class library.

 

Attribute and Indexer

Differences between attributes and indexer:

Each attribute of the class must have a unique name, and each indexer defined in the class must have a unique signature) or the parameter list (so that the indexer can be reloaded ).

The attribute can be static, but the indexer must be an instance Member.

The parameters that can be accessed and passed to the indexer by the access function defined for the indexer, while the attribute access function has no parameters.

 

To declare the class or structure indexer, use the this keyword (similar to the attribute ):

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, see Access Modifier . 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, use the name attribute in the Declaration. For example:

[System. runtime. compilerservices. indexername ("theitem")] Public int this [int Index] // indexer Declaration { } This indexer will have the name theitem. If the name attribute is not provided, the default name of the item is generated. Example 1 the following example shows how to declare private array fields, arr, and 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 member arr [I].C # CopyCode 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 please note that, when the indexer is accessed (for example Console. Write The get accessors are called. Therefore, if Get If the accessor does not exist, a compilation error will occur. Using other values for index 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, declare the class that stores the day of the week. Declared Get Accessors. 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: when setting and retrieving values from any buffer or array accessed by the indexer, always make sure that your code executes the range and type check. Should be Get And set accessors with as many access restrictions as possible. This is true Set The accessors are particularly important. For more information, see Asymmetric accessors (C #Programming Guide) . (Source: msdn)

 

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.