The indexer is a method in C # That allows access to instances of the same category or structure as an array. The indexer is similar to an attribute. The difference is that it uses parameters and uses thisKeyword.
1. Definition syntax of the indexer:
PrivateT [] arr =NewT [100];PublicTThis[IntI] {Get{ReturnArr [I];}Set{Arr [I]=Value ;}}
1) access modifier, which is public. The index type and parameter type must be at least as accessible as the index itself;
2) type T, based on the defined instance type;
3) KEYWORDSThisIf you want to provide the indexer with a name that can be used by another language, you can useName feature: This indexer is renamed to renamed. If the name feature is not provided, the default item name is generated;
[System. runtime. compilerservices. indexername ("Renamed")]Public Int This[IntIndex] {}
4) Get, set accessors, and so the index. Index type can be not int type, such as string;
2. The indexer IN THE INTERFACE
1) Unlike the index-like tool, the interface indexer cannot use modifiers. The accesser has no body, indicating whether the indexer reads or writes data only;
2) When the class uses the same indexer signature to implement more than one interface, to avoid ambiguity, you need to use a fully qualified name, that is, the interface name. This [int Index], for example:
Interface Test1 { Int This [ Int Index] { Get ; Set ;}} Interface Test2 { Int This [ Int Index] { Get ; Set ;}} Class Program { Int [] Arr = New Int [100 ]; Public Int Test1. This [ Int Index] { Get { Return Arr [Index];} Set {Arr [Index] = Value ;}}}
3. Differences between attributes and indexer:
Attribute |
Indexer |
You can call a method just like calling a public data member, |
Allows an object to use array representation to access elements in the object's internal set. |
It can be a static member or an instance Member. |
It must be an instance Member. |
The get accessors of the attribute have no parameters. The set accessors of the attribute contain the implicit value parameter. |
The get and set accessors Of The indexer have the same parameters as those of the indexer. |
You can use the phrase Method for automatically implemented attributes. |
The phrase method is not supported. |