现在的位置: 首页 > 综合 > 正文

索引器 (C#)

2014年01月13日 ⁄ 综合 ⁄ 共 960字 ⁄ 字号 评论关闭
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数
class SampleCollection
{
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 stringCollection = new SampleCollection(
stringCollection[0] = "Hello, World";
System.Console.WriteLine(stringCollection[0]
}
}

C# 并不将索引类型限制为整数。例如,对索引器使用字符串可能是有用的。通过搜索集合内的字符串并返回相应的值,可以实现此类的索引器。由于访问器可被重载,字符串和整数版本可以共存。

例子2:
// 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
{
int i = 0;
foreach (string day in days
{
if (day == testDay
{
return i;
}
i++;
}
return -1;
}

// 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"]
System.Console.WriteLine(week["Made-up Day"]
}
}

抱歉!评论已关闭.