Indexer
Classes, structures, or interfaces are used as Arrays for convenience.
The indexer is used to encapsulate internal sets or arrays.
Definition syntax
[Access modifier] return type this [index type index name]
{
// Get or set method body
}
An index is an attribute.
The index can be used to obtain the item with the key or the serial number with the item.
Set has strong versatility (method names should be remembered)
Add
Add and AddRange
Remove
Remove, RemoveAt
Clear
Clear
Sort
Sort, Reverse
Search
IndexOf, LastIndexOf
Deposit Determination
Contains
Total number of sets
Count attribute
Light Replication
Clone
Index
The set can also be accessed through "subscript", called Index
Namespace Indexer
{
Class Program
{
Static void Main (string [] args)
{
MyCollection mc = new MyCollection ();
Int [] nums = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Added features
Mc. Add (1, 100 );
Mc. AddRange (nums );
// Insert, add a 100
Mc. Insert (1, 3,100 );
// Remove
// Mc. Remove (100 );
Mc. RemoveAt (2 );
// Clear
// Mc. Clear ();
// Read data at 3
Console. WriteLine (mc [2]);
Console. ReadKey ();
}
}
// Manually write a set
Class MyCollection
{
// Int [] nums;
ArrayList al;
// Method used for testing
Private void Test ()
{
This. Clear ();
// This is inside the class, indicating the current instance
// This [3];
}
// Index
// The essence of the index is the attribute; the essence of the attribute is the method.
Public object this [int index]
{
Get {return al [index];}
Set {al [index] = value ;}
}
Public MyCollection ()
{
Al = new ArrayList ();
}
// Add Method
// The worst way
# Region bad Method
// Public int Add (int num)
//{
// If (nums = null)
//{
// Nums = new int [] {num };
//}
// Else
//{
// Int [] temp = new int [nums. Length + 1];
// For (int I = 0; I <nums. Length; I ++)
//{
// Temp [I] = nums [I];
//}
// Temp [temp. Length-1] = num;
// Nums = temp;
//}
// Return nums. Length + 1;
//}
# Endregion
Public int Add (object o)
{
Return al. Add (0 );
}
Public void AddRange (ICollection ic)
{
Al. AddRange (ic );
}
Public void Remove (object o)
{
Al. Remove (o );
}
Public void RemoveAt (int index)
{
Al. RemoveAt (index );
}
Public void Clear ()
{
Al. Clear ();
}
Public void Insert (int index, object o)
{
Al. Insert (index, o );
}
}
}