C # collection series (4): Indexer

Source: Internet
Author: User

1. Overview

The indexer allows instances of classes or structures to be indexed like arrays. The indexer is similar to an attribute, but its accessors use parameters. The indexer syntax allows you to create a client application to use it as a class, structure, or interface for array access. The indexer is often used to encapsulate internal sets or arrays.

For example, assume that there is a class named TempRecord, which represents ten degrees Fahrenheit records at different times within 24 hours. This class contains an array named "temps" of float Type indicating temperature and DateTime representing the date that records temperature. By implementing an indexer in this class, the client can access the temperature in the TempRecord instance through the float temp = tr [4] instead of the float temp = tr. temps [4] syntax. The indexer notation not only simplifies the syntax of client applications, but also enables other developers to understand classes and their usage more intuitively. You can use the indexer to create an index for an object in an array-like manner.

Get accessors return values. Set accessors allocation value. This keyword is used to define the indexer. The value keyword is used to define the value allocated by the set indexer.

The indexer does not need to index based on the integer value. It is up to you to decide how to define a specific search mechanism. The indexer can be overloaded with multiple parameters, for example, when accessing a two-dimensional array.

2. Example:

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

 

Namespace NetTest

{

Public class TestIndexClass

{

Public void Test ()

{

TempRecord tempRecord = new TempRecord ();

// Use the indexer's set accessor

TempRecord [3] = 58.3F;

TempRecord [5] = 60.1F;

 

// Use the indexer's get accessor

For (int I = 0; I <10; I ++)

{

// This example validates the input on the client side. You may

// Choose to validate it in the class that implements the indexer, and throw

// Exception or return an error code in the case of invalid input.

If (I <tempRecord. Length)

{

System. Console. WriteLine ("Element # {0} = {1}", I, tempRecord [I]);

}

Else

{

System. Console. WriteLine ("Index value of {0} is out of range", I );

}

}

 

// Uncomment this code to see how the. NET Framework handles indexer exceptions

// Try

//{

// System. Console. WriteLine ("Element # {0} = {1}", tempRecord [tempRecord. Length]);

//}

// Catch (System. ArgumentOutOfRangeException e)

//{

// System. Console. WriteLine (e );

//}

 

DayCollection week = new DayCollection ();

System. Console. WriteLine (week ["Fri"]);

System. Console. WriteLine (week ["Made-up Day"]);

 

}

}

 

 

Class TempRecord

{

// Array of temperature values

Private float [] temps = new float [10] {56.2F, 56.7F, 56.5F, 56.9F, 58.8F,

61.3F, 65.9F, 62.1F, 59.2F, 57.5F };

// Auto-Implemented Property

System. DateTime date {get; set ;}

// To enable client code to validate input

// When accessing your indexer.

Public int Length

{

Get {return temps. Length ;}

}

// Indexer declaration.

// Input parameter is validated by client

// Code before being passed to the indexer.

Public float this [int index]

{

Get

{

Return temps [index];

}

 

Set

{

Temps [index] = value;

}

}

}

 

 

 

// C # does not limit the index type to an integer. For example, it may be useful for the indexer to use strings. This type of Indexer can be implemented by searching strings in a set and returning corresponding values.

// Because the accessors can be overloaded, the string and integer versions can coexist.

 

Class DayCollection

{

String [] days = {"Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat "};

 

// This method finds the day or returns-1

Private int GetDay (string testDay)

{

Int I = 0;

Foreach (string day in days)

{

If (day = testDay)

{

Return I;

}

I ++;

}

Return-1;

}

 

// The get accessor returns an integer for a given string

Public int this [string day]

{

Get

{

Return (GetDay (day ));

}

}

}

 

 

}

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.