日期:2014-05-18  浏览次数:20973 次

求大能指教:将迭代器实现对集合类枚举,改成索引器来实现
求帮助,将下面的代码改成索引器实现
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];}
}