C # Add an indexer for the class

Source: Internet
Author: User

Yesterday, a friend asked me how to use the indexer in C # and explained it to him. If you ask other people, the answer will not be used. Obviously, because I think the indexer is not commonly used, I forgot it. In fact, we often use the indexer: array [I] when accessing arrays and set elements. when you access the datagridview and gridview: gridview. datakeys [Index] ["cellname"], ADO. net: datareader ["columnname"]. And so on. It is quite necessary to understand this topic.

1. What is the indexer?

The indexer allows instances of classes and structures to be accessed by subscript. This method is similar to accessing elements of arrays and sets, but not just by subscript. For example, it is also possible to access the attributes of objects through attribute values. The indexer is written in a class or structure. Its format is similar:

?
public
object
this[intindex]{    get{returnobjects[int];
}
    set{ objects[int] = value; }}

The indexer is a special attribute and can have get and set accessors and can be reloaded. Object is the type of the returned object. This indicates the class or structure, and INT index indicates the index type. This corresponds to the calling format of the indexer: object [Index. The following example shows how to add an indexer to a car class.

2. Add an indexer for the class

First, create a car class:

?
/// <summary>/// Automobile/// </summary>public
class
Car{    /// <summary>    /// Brand    /// </summary>    publicstringBrand {get;set;
}
    /// <summary>    /// Color    /// </summary>    publicstringColor {get;set;
}
    /// <summary>    /// Overwrite the tostring () method of the object    /// </summary>    /// <returns></returns>    publicoverridestringToString()    {       
return string.Format("A {0} {1}.",this.Color,this.Brand);    }}

The brand and color attributes are added for the car, And the tostring () method is overwritten to display the car information. Then we create the cars class and add the indexer to access the car:

?
/// <summary>/// Automobile collection/// </summary>public
class
Cars{    publicIList<Car> List {get;set;
}
    /// <summary>    /// Indexer accessed with subscript    /// </summary>    /// <Param name = "Index"> subscript </param>    /// <Returns> vehicle </returns>    publicCarthis[intindex]    {       
get { returnthis.List[index]; }    }    /// <summary>    /// Brand-accessed Indexer    /// </summary>    /// <Param name = "brand"> brand </param>    /// <Returns> vehicle </returns>    publicCarthis[stringbrand]    {       
get       
{           
for (inti = 0; i < List.Count; i++)               // There are many cases where the value is false. Therefore, equals is used for comparison,               // Instead of ==. For more information, see my previous article.               // Comparison of "equals" and "=" in C #               //http://www.cnblogs.com/ju2ender/archive/2010/03/21/1691033.html               if(brand.Equals(this.List[i].Brand))                   returnthis.List[i];           
return null;       
}    }}

Cars has a car set, which is written into two indexers, which are accessed by subscript and car brand respectively, forming a heavy load, if no subscript index is written, cars [Index] cannot be used to access car. Next we will write an entry to test whether the indexer works. Three cars will be instantiated: black BMW, red Mercedes, and yellow Porsche.

?
public
class
Program{    publicstaticvoidMain(string[]
args)
    {       
Cars cars = newCars       
{           
List = new
List<Car>
           
{               newCar { Brand ="BMW", Color ="Black"},    //
Black BMW
               newCar { Brand ="Benz", Color ="Red"},     //
Red Mercedes-Benz
               newCar { Brand ="Porsche", Color ="Yellow"}//
Yellow Porsche
           
}       
};       
Console.Title = "Indexer";       
Console.WriteLine(cars[0].ToString());       
Console.WriteLine(cars["Porsche"].ToString());       
Console.ReadLine();    }}

Access by subscript and brand respectively. The following is the running result:

The project name is oop. Click here to download it.

 

From: http://www.cnblogs.com/ju2ender/archive/2010/03/27/1698528.html

 

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.