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

IEnumerable枚举之说??我不太理解,求教!!
我只知道枚举是用字符的形式如(day.monday)来表示数字(如1)

但看书上讲的IEnumerable枚举功能始终不能理解,作用知道,是用于循环迭代的,但为什么叫枚举

这段代码,枚举在哪里??

C# code

foreach(car c in carArray)
{
response.write(c.name)
}



这段代码,枚举在哪里??

------解决方案--------------------
一个Collection要支持foreach方式的遍历,必须实现IEnumerable接口

这里的枚举功能应该是指一个个的列出集合的项
------解决方案--------------------
IEnumerable 和 IEnumerator 是经典的 工厂方法模式
IEnumerator 生产出继承IEnumerable 的实例
也就是 IEnumerable 迭代
在底层要建立一个迭代器
yield 

yield return <expression>;
yield break;
C# code
public class List
{
    //using System.Collections;
    public static IEnumerable Power(int number, int exponent)
    {
        int counter = 0;
        int result = 1;
        while (counter++ < exponent)
        {
            result = result * number;
            yield return result;
        }
    }

    static void Main()
    {
        // Display powers of 2 up to the exponent 8:
        foreach (int i in Power(2, 8))
        {
            Console.Write("{0} ", i);
        }
    }
}
/*
Output:
2 4 8 16 32 64 128 256 
*/

------解决方案--------------------
当然 .NET 2.0 以后 使用Ilist 反省要好多了

C# code
static IEnumerable<int> WithYield()
        {
            for (int i = 0; i < 20; i++)
            {
                Console.WriteLine(i.ToString());
                if(i > 2)
                    yield return i;
            }
        }

------解决方案--------------------
引用楼主 aspnet30 的帖子:
我只知道枚举是用字符的形式如(day.monday)来表示数字(如1)

但看书上讲的IEnumerable枚举功能始终不能理解,作用知道,是用于循环迭代的,但为什么叫枚举

这段代码,枚举在哪里??


C# code
foreach(car c in carArray)
{
response.write(c.name)
}




这段代码,枚举在哪里??

------解决方案--------------------
这个枚举是动词...你要理解它去查汉语词典而不是MSDN...
------解决方案--------------------
其实starts_2000 bhtfg538 
都说得差不多了.
我也不多说了!~

不知道楼主不明白什么呢?
------解决方案--------------------
System.Collections.IEnumerator e= orderstatusinfo.GetEnumerator(); 
while (e.MoveNext()) 

Response.Write(e.Current.ToString()) 
}
底层原理就是 上面说的
就是你的代码的 愿意

更底层的 你用汇编看吧
------解决方案--------------------
唉...程序员也得学语文啊...
------解决方案--------------------
探讨
大汗......
我只想知道哪个地方用了枚举,
是e.movenext?

------解决方案--------------------
见过笨的,没见过这么笨的...

这个枚举是动词不是枚举类型...你要理解它去查汉语词典...
------解决方案--------------------
System.Collections.IEnumerator e= orderstatusinfo.GetEnumerator(); 
while (e.MoveNext()) 

Response.Write(e.Current.ToString()) 



 System.Collections.IEnumerator e= orderstatusinfo.GetEnumerator(); 
可以将e看作是一些数据的集合


e.MoveNext()作用是访问集合中的单个数据

 while (e.MoveNext()) 的作用就是顺序访问集合中的每个数据,直到数据的最后一个