读书人

求大能指教:将迭代器实现对集合类枚举

发布时间: 2012-05-31 12:19:24 作者: rapoo

求大能指教:将迭代器实现对集合类枚举,改成索引器来实现
求帮助,将下面的代码改成索引器实现

C# code
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 + " ");        }    }}


[解决办法]
C# code
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];}
}

读书人网 >C#

热点推荐