关于集合的理解

代码
集合就是实现了IEnumerable接口的类。在实现IEnumerable接口的类上可以使用foreach循环。
 
using System;
using System.Collections;

namespace test
{
    
class test
    {
        
static void Main()
        {
            DayOfWeek d
=new DayOfWeek();
            
//两段代码等价,事实上就是foreach的IL代码
            
//foreach (string s in d)
            
//{
            
//    Console.WriteLine(s);
            
//}
            IEnumerator i=d.GetEnumerator();
            
while (i.MoveNext())
            {
                  Console.WriteLine(i.Current.ToString());
            }
            
        }
    }
    
public class DayOfWeek : IEnumerable
    {
        
#region IEnumerable 成员
        
string[] d_week = { "星期1""星期2""星期3""星期4""星期5""星期6""星期7", };
        
public IEnumerator GetEnumerator()
        {
            
//throw new NotImplementedException();
            for (int i = 0; i < d_week.Length; i++)
            {
                
yield return d_week[i];
            }
        }
        
#endregion
    }
}
原文地址:https://www.cnblogs.com/kakaliush/p/1672412.html