Chinaunix首页 | 论坛 | 博客
  • 博客访问: 304848
  • 博文数量: 174
  • 博客积分: 3061
  • 博客等级: 中校
  • 技术积分: 1740
  • 用 户 组: 普通用户
  • 注册时间: 2006-05-04 22:43
文章分类

全部博文(174)

文章存档

2011年(54)

2010年(14)

2009年(30)

2008年(26)

2007年(27)

2006年(23)

我的朋友

分类: WINDOWS

2009-06-23 17:00:43

.net 支持的迭代从原理上来说均依靠了
IEnumerable or IEnumerable 方式来支持。
其中内置类型的数组由.net内部实现了IEnumerable 因此可以支持支持foreach.
自定义类型大致有如下几种方式:
 
1. 模板特化
 class class1s : IEnumerable
    {
        private List cs;
        public class1s()
        {
            cs = new List();
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return cs.GetEnumerator();
        }
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return cs.GetEnumerator();
        }
    }
2.  采用yield 定制命名迭代
class class3
    {
        private List cs = new List();
        public class3()
        {
            Class1 c1 = new Class1();
            c1.name = "c1";
            Class1 c2 = new Class1();
            c2.name = "c2";
            cs.Add(c1);
            cs.Add(c2);
        }
        public IEnumerator GetEnumerator()
        {
            foreach (Class1 item in cs)
            {
                yield return item;
            }
        }
        public IEnumerable GetClass1Reverse()
        {
            for (int i = cs.Count; i > 0 ; i--)
            {
                yield return cs[i - 1];
            }
        }
    }
 
阅读(463) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~