• 使用yield关键字让自定义集合实现foreach遍历


           一般来说当我们创建自定义集合的时候为了让其能支持foreach遍历,就只能让其实现IEnumerable接口(可能还要实现IEnumerator接口)

    但是我们也可以通过使用yield关键字构建的迭代器方法来实现foreach的遍历,且自定义的集合不用实现IEnumerable接口

    注:虽然不用实现IEnumerable接口 ,但是迭代器的方法必须命名为GetEnumerator() ,返回值也必须是IEnumerator类型

    实例代码以及简单说明如下:

     1     class Person
     2     {
     3         public string Name;
     4         public void SayHi()
     5         {
     6             Console.WriteLine("Hello: {0}",this.Name);
     7         }
     8     }
     9     //非常简单的自定义集合(- -简单到增加,删除,索引器等功能都没有实现) 该类没有实现IEnumerable接口
    10     class PersonList
    11     {
    12         Person[] pers =new Person[4];
    13         public PersonList()
    14         {
    15             pers[0] = new Person() { Name = "1" };
    16             pers[1] = new Person() { Name = "2" };
    17             pers[2] = new Person() { Name = "3" };
    18             pers[3] = new Person() { Name = "4" };
    19 
    20         }
    21         //简单的迭代器方法
    22         public IEnumerator GetEnumerator()
    23         {
    24             
    25             foreach (Person item in pers)
    26             {
    27                 //yield return 作用就是返回集合的一个元素,并移动到下一个元素上
    28                 yield return item;
    29             }
    30 
    31         }
    32     }
    33     class Program
    34     {       
    35         static void Main(string[] args)
    36         {
    37             PersonList list = new PersonList();
    38             foreach (Person item in list)
    39             {
    40                 item.SayHi();
    41             }
    42             Console.ReadLine();           
    43         }
    44     }
  • 相关阅读:
    css,dispaly与visibility
    关于easyui使用的一些错误
    如何修改 node_modules 里的文件
    vue中执行异步函数async和await的用法
    JavaScript中的变量提升本质
    JS 会有变量提升和函数提升
    Weakmap详解
    js中“??“和“?.“怎么用?
    selenium去除特征 undetected_chromedriver
    js 对象嵌套 hook
  • 原文地址:https://www.cnblogs.com/CodeFaker/p/3914698.html
Copyright © 2020-2023  润新知