C # beginner-Use of the index get and set (generic class)

Source: Internet
Author: User

The indexer allows instances of classes or structures to be indexed like arrays. The indexer is similarAttributeThe difference is that their accessors use parameters.

In the following example, a generic class is defined and simple get and set accessors (as the method for allocating and retrieving values) are provided ).ProgramClass creates an instance of this class for the storage string.

 Class Samplecollection <t>
{
Private T [] arr = New T [ 100 ];
Public T This [ Int I]
{
Get
{
Return Arr [I];
}
Set
{
Arr [I] = value;
}
}
}

// This class shows how client code uses the Indexer
Class Program
{
Static Void Main ( String [] ARGs)
{
Samplecollection < String > Stringcollection = New Samplecollection < String > ();
Stringcollection [ 0 ] = " Hello, world " ;
System. Console. writeline (stringcollection [ 0 ]);
}
}
 
 
Indexer Overview

    • You can use the indexer to create an index for an object in an array-like manner.

    • Get Accessors return values.SetThe value allocated by the accessor.

    • This keyword is used to define the indexer.

    • The value keyword is used to defineSetThe value allocated by the 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.

    • The indexer can have multiple parameters, for example, when accessing a two-dimensional array.

This, the class indexer:

The following example shows how to declare a private array field,TempsAnd indexer. You can use the indexer to directly access the instance.Temprecord [I]. Another way to use the indexer is to declare the array as a Public Member and directly access its members.Temprecord. Temps [I].

Note that when accessing the indexer (for exampleConsole. WriteThe get accessors are called. Therefore, ifGetIf the accessor does not exist, a compilation error will occur.

Code
 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 };

// To enable client code to validate input
// When accessing your indexer.
Public Int Length
{
Get { Return Temps. length ;}
}
// Indexer declaration.
// If index is out of range, the temps array will throw the exception.
Public Float This [ Int Index]
{
Get
{
Return Temps [Index];
}

Set
{
Temps [Index] = value;
}
}
}

Class Mainclass
{
Static Void Main ()
{
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 ++)
{
System. Console. writeline ( " Element #{0 }={ 1} " , I, temprecord [I]);
}

// Keep the console window open in debug mode.
System. Console. writeline ( " Press any key to exit. " );
System. Console. readkey ();

}
}
Index with other values

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.

Example 2

Description

In this example, the class for storing the day of the week is declared. DeclaredGetAccessors. It accepts the string (day name) and returns an integer. For example, 0 is returned for Sunday, 1 is returned for Monday, and so on.

Code
//  Using a string as an indexer Value  
Class Daycollection
{
String [] Days = { " Sun " , " Mon " , " Tues " , " Wed " , " Thurs " , " Fri " , " Sat " };

// This method finds the day or returns-1
Private Int Getday ( String Testday)
{

For ( Int J = 0 ; J <days. Length- 1 ; J ++)
{
If (Days [J] = testday)
{
Return J;
}
}

Throw New System. argumentoutofrangeexception (testday, " Testday must be in the form \ "Sun \", \ "Mon \", etc " );
}

// The get accessor returns an integer for a given string
Public Int This [ String Day]
{
Get
{
Return (Getday (day ));
}
}
}

Class Program
{
Static Void Main ( String [] ARGs)
{
Daycollection week = New Daycollection ();
System. Console. writeline (week [" Fri " ]);

// Raises argumentoutofrangeexception
System. Console. writeline (week [ " Made-up day " ]);

// Keep the console window open in debug mode.
System. Console. writeline ( " Press any key to exit. " );
System. Console. readkey ();
}
}
// Output: 5
Reliable Programming

There are two main ways to improve the security and reliability of the indexer:

    • Make sure to combine a type of error handling policy to handle the case where the client code passes in an invalid index value. In the first example before this topic, the temprecord class provides the Length attribute so that client code can verify the input before passing it to the indexer. You can also put the error handling code inside the indexer. Make sure that you record any exceptions caused by the accessors Of The indexer. For more information, seeException Design Guidelines.

    • Should beGetAnd set accessors with as many access restrictions as possible. This is trueSetThe accessors are particularly important. For more information, seeAsymmetric accessors (C # programming guide).

Comparison between attributes and indexer:

The indexer is similar to the attribute. Except for the differences shown in the following table, all rules defined for the property accessors also apply to the indexer accessors.

attribute

indexer

A method can be called just like a public data member.

allows an object to use array representation to access elements in the object's internal set.

access by simple name.

it can be accessed through the indexer.

it can be a static or instance Member.

it must be an instance Member.

The get accessors of the attribute have no parameters.

the Get access device of the indexer has the same parameters as the index table.

the set accessors of the

attribute include the value parameter.

except for value parameters, the set accessors Of The indexer also have the same parameters as those of the indexer.

supports the phrase Method for automatically implemented attributes (C # programming guide) .

the phrase method is not supported.

Related Article

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.