首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

求大能指教:将迭代器实现对集合类枚举,改成索引器来实现解决方法

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

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

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];}
}

热点排行