惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

D
Docker
Apple Machine Learning Research
Apple Machine Learning Research
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园 - 三生石上(FineUI控件)
月光博客
月光博客
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
WordPress大学
WordPress大学
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
M
MIT News - Artificial intelligence
腾讯CDC
B
Blog RSS Feed
H
Help Net Security
J
Java Code Geeks
有赞技术团队
有赞技术团队
Y
Y Combinator Blog
博客园_首页
Last Week in AI
Last Week in AI
博客园 - 【当耐特】
博客园 - Franky
B
Blog
MongoDB | Blog
MongoDB | Blog
博客园 - 叶小钗
Martin Fowler
Martin Fowler

博客园 - protorock

WPF:通过Window.DataContext实现窗口间传值 How to add dependency on a Windows Service AFTER the service is installed 关于Local System/Local Service/Network Service账户 vs2010 c# 管理win7防火墙 WIN7系统中连接点(Junction Points) 程序集强名称(Strong Name)延迟签名与签名 VISUAL STUDIO 2010 单元测试 Windows Server 2008 R2上Ext.net 生产环境搭建 在Windows7 (SP1)配置IIS7.5 + .Net Framework 4.0.30319 将Google Map 与ASP.NET AJAX 扩展集成 web.config 加密步骤 - protorock - 博客园 GridView 与自定义对象的绑定和分页 在Windows 2003 中发布 ASP.NET 2.0 + SQL SERVER Express SQL Server 2005 Express Edition 用户实例 在 windows2003 Server VS2005 安装 .Net 3.0 .net framework 2.0,3.0与3.5之间的关系 SharpMap AjaxMapControl 中 Zoomin/Zoomout 操作时冻结问题 Sharpmap AjaxMapControl 分析 HTTP 协议概要(二) 持久连接
实现泛型IEnumerable接口
protorock · 2013-07-25 · via 博客园 - protorock

用C#实现一个类的IEnumerable接口时有两种方法:1)实现非泛型IEnumerable接口;2)实现泛型IEnumerable(T)接口。如果采用方法1,当集合元素T是值类型时,将涉及到巨多的boxing和unboxing操作。因此,理所当然地采用方法2;

例如,以下代码采用方法2实现枚举从指定偏移开始所有整数

using System.Collections.Generic;
class Ints : IEnumerable<int> 
{ private readonly int offset; public Ints(int o) { offset = o; } public IEnumerator<int> GetEnumerator()
 { int i = offset; while( true ) yield return i++; } }

编译时产生如下错误:

error CS0535: 'Ints' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'

而我们想要实现的是泛型的IEnumerable而不是非泛型的IEnumerable接口!怎么办呢?

查阅MSDN在线文档可知:泛型IEnumerable继承自非泛型IEnumerable。所有,在上述代码中加入:

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
  return GetEnumerator();
}
这样,非泛型方法转而调用泛型方法,从而不需要再去实现非泛型的IEnumerable接口了。