日期:2014-05-18 浏览次数:21428 次
public class DaysOfTheWeek : System.Collections.IEnumerable
{
string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < days.Length; i++)
{
yield return days[i];
}
}
}
class TestDaysOfTheWeek
{
static void Main()
{
// Create an instance of the collection class
DaysOfTheWeek week = new DaysOfTheWeek();
// Iterate with foreach
foreach (string day in week)
{
System.Console.Write(day + " ");
}
}
}
public class DaysOfTheWeek
{
private string[] days = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" };
public string this[int index]
{
get { return this.days[index]; }
}
public int Count
{
get { return this.days.Length; }
}
}
class TestDaysOfTheWeek
{
static void Main()
{
DaysOfTheWeek week = new DaysOfTheWeek();
for (int i = 0; i < week.Count; i++)
{
System.Console.Write(week[i] + " ");
}
}
}
------解决方案--------------------
1、改成枚举类型更简单
public enum DaysOfWeek{Sun,Mon,Tues,Weds,Thur,Fri,Sat}
2、索引器
public string this[int index]
{
get{if(index<0 || index > this.days.Length) return string.Empty;return this.days[index];}
}