C#笔记12:索引器
本章概要:
1:索引器概述
2:示例
1:索引器概述
-
使用索引器可以用类似于数组的方式为对象建立索引。
-
get 访问器返回值。set 访问器分配值。
-
this 关键字用于定义索引器。
-
value 关键字用于定义由 set 索引器分配的值。
-
索引器不必根据整数值进行索引,由您决定如何定义特定的查找机制。
-
索引器可被重载。
-
索引器可以有多个形参,例如当访问二维数组时。
2:示例
C# 并不将索引类型限制为整数。例如,对索引器使用字符串可能是有用的。通过搜索集合内的字符串并返回相应的值,可以实现此类索引器。由于访问器可被重载,字符串和整数版本可以共存。
// 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) { for (int j = 0; j < days.Length; j++) { if (days[j] == testDay) { return j; } } throw new System.ArgumentOutOfRangeException(testDay, "testDay must be in the form /"Sun/", /"Mon/", etc"); } // 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"]); // Raises ArgumentOutOfRangeException System.Console.WriteLine(week["Made-up Day"]); // Keep the console window open in debug mode. System.Console.WriteLine("Press any key to exit."); System.Console.ReadKey(); } } // Output: 5