Using the indexer, We Can index classes, structures, and interfaces like using arrays. You need to use the this keyword to define the indexer in the class and structure.
- Using system;
- Using system. Collections. Generic;
- Using system. text;
- Namespace consoletest
- {
- Class mainclass
- {
- Static void main ()
- {
- Indexerdemo demo = new indexerdemo ();
- Int result = demo [3];
- Console. writeline (result); // output 67
- }
- }
- Class indexerdemo
- {
- Private int [] arrs = new int [] {5, 8, 54, 67, 25, 1 };
- Public int this [int Index]
- {
- Get
- {
- Return arrs [Index];
- }
- }
- }
- }
In addition to using the indexer, parameters are required. Other features are similar to attributes.
Note:
1. Using the indexer, you can operate classes, structures, and interfaces like using arrays.
2. Integer indexes are not required.
3. Support multiple Loads
4. Multiple parameters are allowed.
Refer to msdn.
Using the indexer to implement a simple collection class
- Using system;
- Using system. Collections. Generic;
- Using system. text;
- Using system. collections;
- Namespace demo
- {
- Class demo3
- {
- Static void main ()
- {
- Myarray arr = new myarray ();
- Arr. Add ("hello ");
- Arr. Add ("world ");
- Arr. Add ("Net ");
- For (INT I = 0; I <arr. length; I ++)
- {
- Console. writeline (ARR [I]);
- }
- }
- }
- Class myarray
- {
- Private string [] _ items = new string [5];
- Private int _ size = 0;
- Public void add (string item)
- {
- _ Items [_ SIZE] = item;
- _ SIZE ++;
- }
- Public String This [int Index]
- {
- Get
- {
- Return _ items [Index];
- }
- }
- Public int Length
- {
- Get
- {
- Return _ size;
- }
- }
- }
- }