A well documented explanation from MSDN: http://msdn.microsoft.com/en-us/library/2549tw02.aspx
To declare an indexer on a class or struct, use the this keyword, as in this example:
public int this[int index] // Indexer declaration
{
// get and set accessors
}
My Example modified from MSDN's example for indexers:
=============================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExampleForIndexers02
{
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;
}
}
public float Total
{
get
{
float fln = 0;
for (int i = 0; i < this.Length; i++)
{
fln = fln + this[i];
}
return fln;
}
}
}
class MainClass
{
static void Main()
{
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++)
{
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.WriteLine("{0}",tempRecord.Length);
System.Console.WriteLine("{0}", tempRecord.Total);
System.Console.ReadKey();
}
}
}
0 comments:
Post a Comment