《随笔二十三》——C#中的 “ 枚举器、可枚举类 、和 迭代器 ”

目录

枚举器 和 可枚举类型 (336P)

IEnumerator 接口 (337P)

IEnumerable 接口

使用 IEnumerable 和 IEnumerator 接口来使某个类成为可枚举类型 340P

迭代器块(341P)

使用迭代器来创建枚举器 (344P)

使用迭代器来创建可枚举类型 (346)


​​​​​​枚举器 和 可枚举类型 (336P)


  •   每一个可枚举的类型都有一个 GetEnumerator 方法,对于有枚举器的类型而言, 获取一个对象的枚举器的方法是调用对象的 GetEnumerator 方法。实现 GetEnumerator 方法的类型称为可枚举类型。数组就是可枚举类型。 

下图演示了可枚举类型和枚举器之间的关系: 

枚举器和可枚举类型概览
namespace HelloWorld_Console
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] MyArray = { 10, 11, 12, 13, 45, 77, 66 };
// 数组是可枚举类型,那么该语句调用的是数组中的 GetEnumerator()方法,来获取枚举器
            IEnumerator ie = MyArray.GetEnumerator(); 
            while(ie.MoveNext()) // 从当前的有效位置移到下一位置
            {
                int i = (int)ie.Current; // 获取当前位置的元素
                Write($"{i},");
            }
        }
    }
}

 


IEnumerator 接口 (337P)


如果一个 枚举器它实现 IEnumerator接口,那么该接口将包含三个函数成员: 

  • Current, MoveNext, and Reset。

下图中 枚举器是一个叫做 ArrEnumerator 类的实例:

小集合的枚举器

 


IEnumerable 接口


如果一个类实现了 IEnumerable 接口 , 那么就称为该类是可枚举类 或者是称该类是 可枚举类型的。 该接口只存在唯一的方法 GetEnumerator , 那么该方法可以返回可以枚举类型的枚举器。


使用 IEnumerable 和 IEnumerator 接口来使某个类成为可枚举类型 340P


namespace HelloWorld_Console
{
    class ColorEnumerator : IEnumerator 
    {
        string[] colors;
        int position = -1; // 枚举器的起始位置,在第一个元素之前
        public ColorEnumerator(string [] theColors)
        {
            colors = new string[theColors.Length];
            for(int i=0;i<theColors.Length;++i)
            {
                colors[i] = theColors[i]; 
            }
        }
        public object Current
        {
            get
            {
                if(position == -1) // 如果枚举器当前的位置是第一个元素之前的位置
                {
                    throw new InvalidOperationException();
                }
                if(position >= colors.Length) // 如果枚举器的位置已在最后一个元素之后的位置
                {
                    throw new InvalidOperationException();
                }
                return colors[position]; // 返回当前位置的元素
            }
        }
      

        public bool MoveNext()
        {
            if(position < colors.Length -1) // 如果当前的 position 在数组的正确范围内
            {
                ++position;
                return true;
            }
            return false;
        }

        public void Reset()
        {
            position = -1; // 重置枚举器的位置,到第一个元素之前
        }
    }

    class Spectrum : IEnumerable
    {
        string[] Colors = { "violet", "blue", "cyan", "green", "yellow", "orange", "red" };
        public IEnumerator GetEnumerator() //  获取一个枚举器
        {
            return new ColorEnumerator(Colors);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Spectrum spectrum = new Spectrum();
            foreach(string tt in spectrum)
            {
                Write($"{tt},");
            }
        }
    }
}

 


迭代器块(341P)


迭代器块是带有一个或多个yield语句的代码块。以下 种代码块 都可以是迭代器块:

  • 方法主体
  • 访问器主体
  • 运算符主体

迭代器块有两个特殊语句:

  • yield return语句指定要返回的序列中的下一项。
  • yield break语句指定序列中没有更多的项。

可以根据迭代器块的返回类型, 你可以让迭代器产生枚举器或可枚举类型:

根据指定的返回类型,可以让迭代器产生枚举器或可枚举类型

使用迭代器来创建枚举器 (344P)


namespace HelloWorld_Console
{
   class MyClass
    {
        public IEnumerator<string> GetEnumerator()
        {
            return BlackAndWhite(); // 返回枚举器
        }
        public IEnumerator<string> BlackAndWhite() // 迭代器
        {
            yield return "black";
            yield return "gray";
            yield return "white";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            foreach(string tt in mc)
            {
                WriteLine(tt);
            }
        }
    }
}

使用迭代器来创建可枚举类型 (346)


namespace HelloWorld_Console
{
   class MyClass
    {
        public IEnumerator<string> GetEnumerator()
        {
            IEnumerable<string> myEnumerable = BlackAndWhite();
            return myEnumerable.GetEnumerator();
        }
        public IEnumerable<string> BlackAndWhite()
        {
            yield return "black";
            yield return "gray";
            yield return "white";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            foreach (string shade in mc)
                Console.Write("{0} ", shade);
            foreach (string shade in mc.BlackAndWhite())
                Console.Write("{0} ", shade);
        }
    }
}

 

静态网业模板,关于花卉的 body { background-color:#c0c0c0; font-family:Arial, Helvetica, sans-serif; padding:0; font-size:12px; margin:0px auto auto auto; color:#000000; } a{ color:#990000; } .clear{ clear:both; } p{ padding:5px 0 5px 0; margin:0px; text-align:justify; line-height:19px; } p.details{ padding:5px 15px 5px 15px; font-size:11px; } p.details_cart{ clear:both; padding:25px 30px 5px 0px; font-size:11px; font-style:italic; } p.more_details{ padding:25px 20px 0px 20px; font-size:11px; } #wrap{ width:900px; height: auto; margin:auto; background-color:#FFFFFF; } .header{ width:900px; height:181px; background:url(images/header.jpg) no-repeat center; } .logo{ padding:0 0 0 30px; } /*-----------------------------menu-------------------*/ #menu{ width:628px; height:41px; margin:55px 0 0 26px; background:url(images/menu_bg.jpg) no-repeat center; } #menu ul{ display:block; list-style:none; padding:9px 0 0 10px; margin:0px; } #menu ul li{ display:inline; padding:0px; margin:0px; height:27px; } #menu ul li a{ height:27px; display:block; padding:0px 10px 0 10px; margin:0 4px 0 4px; _margin:0 2px 0 2px; float:left; text-decoration:none; text-align:center; color:#fff; font-size:13px; line-height:27px; } #menu ul li.selected a{ height:27px; display:block; padding:0px 10px 0 10px; margin:0 5px 0 5px; float:left; text-decoration:none; text-align:center; color:#fff; font-size:13px; line-height:27px; background:url(images/menu_bt_bg.gif) repeat-x center; } #menu ul li a:hover{ background:url(images/menu_bt_bg.gif) repeat-x center; } /*----------------crumb_nav------------------*/ .crumb_nav{ padding:5px 0 10px 0px; } .crumb_nav a{ color:#990000; } span.red{ color:#990000; } .price{ font-size:14px; padding:0 0 0 15px; margin:2px 0 5px 0; } span.colors{ padding:2px 2px 0 2px; } /*------------------------------------center content--------------------*/ .center_content{ width:900px; padding:0px 0 0 0; background:url(images/center_bg.gif) repeat-y center; } .left_content{ width:490px; float:left; padding:20px 0 20px 20px; } .right_content{ width:370px; float:left; padding:20px 0 20px 20px; } .title{ color:#a81f22; padding:0px; float:left; font-size:19px; margin:10px 0 10px 0; } span.title_icon{ float:left; padding:0 5px 0 0; } .prod_title{ color:#a81f22; padding:5px 0 0 15px; font-size:13px; } a.more{ font-style:italic; color:#a81f22; float:right; text-decoration:none; font-size:11px; padding:0px 15px 0 0 ; } .about{ width:337px; clear:both; background:url(images/border.gif) no-repeat bottom center; padding:0 0 20px 0; } img.right{ float:right; padding:0 0 0 10px; } .right_box{ width:170px; float:left; padding:10px 0 0 0; } /*--------feat_prod_box-----------*/ .feat_prod_box{ padding:10px 0 10px 0; margin:0 20px 20px 0; border-bottom:1px #b2b2b2 dashed; clear:both; } .feat_prod_box_details{ padding:10px 0 10px 0; margin:0 20px 10px 0; clear:both; } .prod_img{ float:left; padding:0 5px 0 0; text-align:center; } .prod_det_box{ width:295px; float:left; padding:0 0 0 15px; position:relative; } .box_top{ width:295px; height:9px; background:url(images/box_top.gif) no-repeat center bottom; } .box_center{ width:295px; height:auto; background:url(images/box_center.gif) repeat-y center; } .box_bottom{ width:295px; height:9px; background:url(images/box_bottom.gif) no-repeat center top; } .new_prod_box{ float:left; text-align:center; padding:10px; } .new_prod_box a{ padding:5px 0 5px 0; color:#b5b5b6; text-decoration:none; display:block; } .new_prod_bg{ width:132px; height:119px; text-align:center; background:url(images/new_prod_box.gif) no-repeat center; position:relative; } .new_icon{ position:absolute; top:0px; right:0px; z-index:200; } .special_icon{ position:absolute; top:0px; _top:6px; right:2px; z-index:250; } img.thumb{ padding:10px 0 0 0; } .new_products{ clear:both; padding:0px; } ul.list{ clear:both; padding:10px 0 0 20px; margin:0px; } ul.list li{ list-style:none; padding:2px 0 2px 0; } ul.list li a{ list-style:none; text-decoration:none; color:#000000; background:url(images/left_menu_bullet.gif) no-repeat left; padding:0 0 0 17px; } ul.list li a:hover{ text-decoration:underline; } /* demo */ div.demolayout { width:460px; margin: 0 0 20px 0; } ul.demolayout { list-style-type: none; float: left; margin:0px; padding:0px; } ul.demolayout li { margin: 0 10px 0 0; float: left; } .tab{ border:1px #DFDFDF solid; padding:0 0 25px 0; } ul.demolayout a { float: left; display: block; padding: 5px 25px; border: 1px solid #DFDFDF; border-bottom: 0; color: #666; background: #eee; text-decoration: none; font-weight: bold; } ul.demolayout a:hover { background: #fff; } ul.demolayout a.active { background: #fff; padding-bottom: 5px; cursor: default; color:#931A1D; } .tabs-container { clear: left; padding:0px; } /*-----------------------languages_box---------*/ .languages_box{ padding:0 0 5px 0; float:left; } .languages_box a{ padding:0 2px 0 2px; } .languages_box a.selected{ padding:2px 2px 0 2px; border:1px #CCCCCC solid; } .currency{ float:left; padding:0 0 0 20px; } .currency a{ text-decoration:none; color:#333333; padding:3px; border:1px #eeedee solid; } .currency a.selected{ text-decoration:none; color:#fff; padding:3px; border:1px #eeedee solid; background-color:#FF9900; font-weight:bold; } .currency a:hover{ border:1px #990000 solid; } /*------------------------cart---------------------*/ .cart{ width:337px; float:left; height:40px; margin:10px 0 10px 0; background:url(images/border.gif) no-repeat bottom center; padding:0 0 20px 0; } .home_cart_content{ float:left; padding:3px; border:1px #eeedee solid; margin:10px 0 0 15px; } a.view_cart{ display:block; float:left; margin:12px 0 0 10px; color:#990000; } /*---------------contact_form------------------*/ .contact_form{ width:355px; float:left; padding:25px; margin:20px 0 0 15px; _margin:20px 0 0 5px; border:1px #DFD1D2 dashed; position:relative; } .form_row{ width:335px; _width:355px; clear:both; padding:10px 0 10px 0; _padding:5px 0 5px 0; color:#a53d17; } label.contact{ width:75px; float:left; font-size:12px; text-align:right; padding:4px 5px 0 0; color: #333333; } input.contact_input{ width:253px; height:18px; background-color:#fff; color:#999999; border:1px #DFDFDF solid; float:left; } textarea.contact_textarea{ width:253px; height:120px; font-family:Arial, Helvetica, sans-serif; font-size:12px; color: #999999; background-color:#fff; border:1px #DFDFDF solid; float:left; } input.register{ width:71px; height:25px; border:none; cursor:pointer; text-align:center; float:right; color:#FFFFFF; background:url(images/register_bt.gif) no-repeat center; } a.contact{ width:53px; height:24px; display:block; float:right; margin:0 0 0 10px; background:url(images/contact_bt.gif) no-repeat center; text-decoration:none; text-align:center; line-height:24px; color:#fff; } a.checkout{ width:71px; height:25px; display:block; float:right; margin:10px 30px 0 10px; background:url(images/register_bt.gif) no-repeat center; text-decoration:none; text-align:center; line-height:25px; color:#fff; } a.continue{ width:71px; height:25px; display:block; float:left; margin:10px 0 0 0px; background:url(images/register_bt.gif) no-repeat center; text-decoration:none; text-align:center; line-height:25px; color:#fff; } .terms{ padding:0 0 0 80px; } .form_subtitle{ position:absolute; top:-11px; left:7px; width:auto; height:20px; background-color:#990000; text-align:center; padding:0 7px 0 7px; color:#FFFFFF; font-size:11px; line-height:20px; } /*--------------cart_table-------------*/ .cart_table{ width:440px; border:1px #CCCCCC solid; text-align:center; } tr.cart_title{ background-color:#DFDFDF; } td{ padding:3px; } td.cart_total{ text-align:right; padding:5px 15px 5px 0; } img.cart_thumb{ border:1px #b2b2b2 solid; padding:2px; } /*--------------*/ div.pagination { width:420px; padding:5px; margin:5px; text-align:center; float:left; clear:both; font-size:10px; } div.pagination a { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #ddd; text-decoration: none; color: #990000; } div.pagination a:hover, div.pagination a:active { border:1px solid #990000; color: #fff; background-color: #990000; } div.pagination span.current { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #990000; font-weight: bold; background-color: #990000; color: #FFF; } div.pagination span.disabled { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #f3f3f3; color: #ccc; } /*---------------footer------------------------*/ .footer{ height:100px; border-top:1px #b2b2b2 dashed; background:url(images/footer_bg.gif) no-repeat bottom; } .left_footer{ float:left; padding:10px 0 0 10px; } .right_footer{ float:right; padding:10px 10px 0 0; } .footer a{ text-decoration:none; padding:0 5px 0 5px; color:#afaeaf; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值