Today an indexer is defined in a class, but when a property called item is defined, a compiler error is found:
1 namespaceTest2 {3 class Program4 {5 Static voidMain (string[] args)6 {7Person p =NewPerson ();8p["name"] ="Hello";9Console.WriteLine (p[3]);TenConsole.WriteLine (p["name"]); One console.readline (); A - } - } the - Public class Person - { - Private stringname; + Private intAge ; - Private Char[] ch = {'Q','R','m','D'}; + A Public Char This[intIndex] at { - Get{returnCh[index];} - Set{Ch[index] =value;} - } - Public stringMSG {Get;Set; } - in Public Object This[stringIndex] - { to Get + { - Switch(Index) the { * Case" Age": $ returnAge ;Panax Notoginseng Case "name": - returnname; the default : + return NULL; A } the } + Set - { $ Switch(Index) $ { - Case "name": -Name =value. ToString (); the Break; - Case " Age":WuyiAge = (int) value; the Break; - } Wu } - } About //Public string Item {get; set;} $ - } -}
View Code
Decompile the program to see the true colors of the indexer:
We found that Microsoft has made our defined indexer a property called item, no wonder that its own definition of the Item property will not be compiled by
We also found that this indexer only provides two methods, in order to facilitate the operation of the class members outside.
Also, this automatic attribute msg, Microsoft also automatically generated a field.
The true colors of indexers