索引指標本質就是一個含參數屬性,其使用方法和數組類似。但索引指標的參數並不只限於 int, string 也可以:MyWeek myWeek = new MyWeek();
for (int i = 1; i <= myWeek.Length; i++)
{
Console.WriteLine(myWeek[i]);
}
下面是一個簡單的例子:
1. MyWeek 類
/// <summary>
/// 索引指標的實質是含參屬性,
/// 參數並不只限於 int, string 也可以。
/// </summary>
public class MyWeek
{
public int Length
{
get { return 7; }
}
/// <summary>
/// 使用 int 作為參數的索引指標
/// </summary>
/// <param name="Index"></param>
/// <returns></returns>
public string this[int Index]
{
get
{
string dayName;
switch (Index)
{
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "";
break;
}
return dayName;
}
}
/// <summary>
/// 使用 string 作為參數的索引指標
/// </summary>
/// <param name="dayName"></param>
/// <returns></returns>
public int this[string dayName]
{
get
{
dayName = dayName.ToLower();
switch (dayName)
{
case "monday":
return 1;
case "tuesday":
return 2;
case "wednesday":
return 3;
case "thursday":
return 4;
case "friday":
return 5;
case "saturday":
return 6;
case "sunday":
return 7;
default:
return -1;
}
}
}
}
2. 使用方法
MyWeek myWeek = new MyWeek();
for (int i = 1; i <= myWeek.Length; i++)
{
Console.WriteLine(myWeek[i]);
}
string dayName;
for (int i = 1; i <= myWeek.Length; i++)
{
dayName = myWeek[i];
Console.WriteLine(myWeek[dayName].ToString());
}
3. 輸出結果
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday
1
2
3
4
5
6
7
相關文章:實現 foreach 功能
本文地址:http://www.cnblogs.com/anjou/archive/2007/07/06/808206.html