The true colors of indexers

Source: Internet
Author: User

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

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.