C # Use of Indexer

Source: Internet
Author: User

I recently came into contact with indexer. Generally speaking, indexer refers to something similar to a property defined in a class. The indexer is a new class member in. net. Similar to class attributes. Some people simply call it an attribute with parameters.

The indexer can quickly locate a group member in a class. Next let's take a lookCode:

Indexer

 Class  Indexerclass
{
Private Int [] Arr = New Int [ 100 ];
Private String [] Names = New String [ 100 ];
Public Int This [ Int Index]
{
Get
{
If (Index < 0 | Index > = 100 )
{
Return - 1 ;
}
Else
{
Return Arr [Index];
}
}
Set // The get and set methods of the indexer are compiled by the compiler into the get_item and sge_item methods.
{
If (Index > = 0 && Index < 100 )
{
Arr [Index] = Value;
}
}
}
Public Int This [ String Key] // The indexer parameter is also a string, not necessarily an int.
{
Get
{
Return Getnumber (key );
}
}
Public Int Getnumber ( String Gender)
{
If (Gender = " Boy " )
{
Return 1 ;
}
Else If (Gender = " Girl " )
{
Return 0 ;
}
Else
{
Return - 1 ;
}
}
}

Most of the index parameters are 'int' type, but they can also be other types, such as 'string.

 Static    Void  Main (  String  [] ARGs)
{
Indexerclass indexertest = New Indexerclass ();
For ( Int I = 0 ; I < 10 ; I ++ )
{
Indexertest [I] = I + 2 ; // For class objects, you can operate the arrays in the objects just like an array.
}
For ( Int I = 0 ; I < 10 ; I ++ )
{
Console. writeline (indexertest [I]);
}
Console. readkey ();
}

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.