我看书上说,只有实现了IEnumerable接口的类才能使用foreach,为什么下面的情况,没有继承IEnumerable也可以啊。using System;
using System.Collections;namespace Array
{
public class HelloCollection //: IEnumerable (这里写不写都行)
{
public IEnumerator GetEnumerator()
{
yield return "hello";
yield return "world";
}
} public class Test
{
static void Main()
{
HelloCollection hc = new HelloCollection();
foreach (string str in hc)
{
Console.WriteLine(str);
}
}
}
}
using System.Collections;namespace Array
{
public class HelloCollection //: IEnumerable (这里写不写都行)
{
public IEnumerator GetEnumerator()
{
yield return "hello";
yield return "world";
}
} public class Test
{
static void Main()
{
HelloCollection hc = new HelloCollection();
foreach (string str in hc)
{
Console.WriteLine(str);
}
}
}
}
解决方案 »
- 接着发帖,怎么就不能跳转到第二个if语句里的页面呢?
- 如何控件flowlayoutpanel只有垂直滚动条?
- 请教各位大侠,如何显示搜索到的关键字所在句
- C# 项目开发平台搭建
- 求助!把下面VB的代码转换成C#的,万分感激!
- ★★★★★ 小白又来请教了:未将对象引用设置到对象实例 ★★★★★
- 树的复选框选中问题
- c#远程连接excel
- 请问如何保存8位的位图?
- 查了很多资料竟然都没有,Winform中,如何在TreeView中点击右键,选中当前节点,并且弹出一个菜单!
- 高手请进,关于循环取数
- 大师们,winform datagridview有没有一个属性能显示目前统计的条数?或者bindinnavigator
http://topic.csdn.net/u/20090508/09/26e63539-ada5-4808-9c9b-2fe7e53f3409.html从来没有“只有实现了IEnumerable接口的类才能使用foreach”的说法...你看的书是垃圾,可以扔掉了...
书上说的是Hello对象,HelloCollection 实现Hello对象的迭代
也就是说 foreach(Hello h in hc)的情况是需要实现IEnumerable的
{
yield return "hello";
yield return "world";
}
事实上,这个在底层应该是从对象中动态调用方法。参考后期绑定。有点类似这个,是用反射来的。认的是"GetEnumerator",而不是接口。但是多半是在没有找到接口时才会去尝试反射调用吧。要不.net不可能有这么高的效率。