您的位置:首页 > 编程语言 > C#

索引器 (C#)

2010-05-19 16:00 204 查看
索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数
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"]

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: