通過索引器可以方便使用類中的數組(或集合)成員:
using System;
class MyClass
{
private float[] fs = new float[3] { 1.1f, 2.2f, 3.3f };
/* 屬性 */
public int Length
{
get { return fs.Length; }
set { fs = new float[value]; }
}
/* 索引器 */
public float this[int n]
{
get { return fs[n]; }
set { fs[n] = value; }
}
}
class Program
{
static void Main()
{
MyClass obj = new MyClass();
for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 1.1/2.2/3.3
for (int i = 0; i < obj.Length; i++) obj[i] += 5.5f;
for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 6.6/7.7/8.8
obj.Length = 5;
for (int i = 0; i < obj.Length; i++) Console.WriteLine(obj[i]); // 0/0/0/0/0
Console.ReadKey();
}
}
可用其他值做索引類型:
using System;
class MyClass
{
public int this[string str]
{
get { return str.Length; }
}
}
class Program
{
static void Main()
{
MyClass obj = new MyClass();
Console.WriteLine(obj["123"]); // 3
Console.WriteLine(obj["abcd"]); // 4
Console.ReadKey();
}
}