During the process of program development, it is often necessary to access a set of objects, usually by creating an array list that is accessed by manipulating an array. The index indicator provided by C # allows us to easily and efficiently access a set of objects. Typically, we create a container class to store objects, and provides the corresponding operation method by implementing the enumerator interface. The following sample program demonstrates how to create and use an index indicator.
First step: Create a container class
In this code, ArrayList is used to enable us to manage objects using ArrayList features, and to implement IEnumerator interfaces, provide methods such as Movenext,reset, and enable the container class to support foreach operations.
class Employees:ienumerator//To enable container support (FOREACH ...). In ..... operation, you must implement the IEnumerator interface)
{
Private ArrayList m_employees;
Defines a ArrayList object
private
int m_maxemployees;
Defines the maximum number of objects that a container can accept
//constructor, create a ArrayList object, and define the maximum number of objects that can be accepted
public Employees (int maxemployees)
{
M_m Axemployees = maxemployees;
M_employees = new ArrayList (maxemployees);
}
//CREATE INDEX indicator by index ID
Public Employee
this[
Int index]
{
Get
{
if (Index < 0 | | | index > M_EMPLOYEES.COUNT-1)
{
return null;
Return (Employee) M_employees[index];
}
Set
{
if (Index <0 | | index > M_MAXEMPLOYEES-1)
{
Retu RN;
}
M_employees.insert (index,value);
}
//Custom Index indicator
Public Employee
this[
String SSN]
{
Get
{
Emp LoyEE empreturned = null;
foreach (Employee employee in m_employees)
{
if (employee). SSN = = SSN)
{
empreturned = employee;
Break
}
}
return empreturned
}
//provide the number of objects in the container
public
int Length
{
Get
{
return m_employees.count ;
}
//Implementation IEnumerator interface
Public IEnumerator GetEnumerator ()
{
Return m_employees.ge Tenumerator ();
}
public bool MoveNext ()
{
return m_employees.getenumerator (). MoveNext ();
}
public void Reset ()
{
M_employees.getenumerator (). Reset ();
}
Public object current
{
Get
{
return m_employees.getenumerator (). Current;
}
}
}