- The difference between an attribute and an index
Property |
Indexer |
Identify by name |
Identifying with a parameter list |
Access by simple name |
Access by [] operator |
Can be modified with static |
cannot be modified with static |
Get accessor has no parameters |
The get accessor has the same argument list as the index |
The set accessor contains an implicit value parameter |
In addition to the value parameter, the index's set accessor has the same argument list as the index |
- Example
1 class Person2 {3 Private ReadOnly string[] _data =New string[6];4 Private ReadOnly string[] _keys = {5 "Name"," Age","Sex"6 };7 8 //Note: The program uses two methods to index:9 //one is an integer to subscript, and the other is the string (keyword name) as subscriptTen Public string This[intIDX] One { A Set - { - if(IDX >=0&& IDX <_data. Length) the_DATA[IDX] =value; - } - Get - { + if(IDX >=0&& IDX <_data. Length) - return_data[idx]; + return NULL; A } at } - Public string This[stringKey] - { - Set - { - intIDX =FindKey (key); in This[IDX] =value; - } to Get + { - return This[FindKey (Key)]; the } * } $ Private intFindKey (stringkey)Panax Notoginseng { - for(inti =0; I < _keys. Length; i++) the if(_keys[i] = = key)returni; + return-1; A } the Static voidMain (string[] args) + { -Person record =NewPerson (); $record[0] ="Jhon Snow"; $record[1] =" at"; -record["Sex"] ="male"; -Console.WriteLine (record["Name"]); theConsole.WriteLine (record[" Age"]); -Console.WriteLine (record[2]);Wuyi console.readline (); the } -}
C # Indexer