关于C#中yield关键字的深入解析

前言

前段时间了解到yield关键字,一直觉得还不错。今天给大家分享一下yield关键字的用法。yield return 返回集合不是一次性返回所有集合元素,而是一次调用返回一个元素。具体如何使用yield return 返回集合呢?我们一起往下面看吧。

yield使用介绍

yield return 和yield break:

我们看下平常循环返回集合的使用操作(返回1-100中的偶数):

 class Program
 {
 static private List<int> _numArray; //用来保存1-100 这100个整数

 Program() //构造函数。我们可以通过这个构造函数往待测试集合中存入1-100这100个测试数据
 {
  _numArray = new List<int>(); //给集合变量开始在堆内存上开内存,并且把内存首地址交给这个_numArray变量

  for (int i = 1; i <= 100; i++)
  {
  _numArray.Add(i); //把1到100保存在集合当中方便操作
  }
 }

 static void Main(string[] args)
 {
  new Program();

  TestMethod();

 }

 //测试求1到100之间的全部偶数
 static public void TestMethod()
 {
  foreach (var item in GetAllEvenNumberOld())
  {
  Console.WriteLine(item); //输出偶数测试
  }
 }

 /// <summary>
 /// 使用平常返回集合方法
 /// </summary>
 /// <returns></returns>
 static IEnumerable<int> GetAllEvenNumberOld()
 {
  var listNum = new List<int>();
  foreach (int num in _numArray)
  {
  if (num % 2 == 0) //判断是不是偶数
  {
   listNum.Add(num); //返回当前偶数

  }
  }
  return listNum;
 }
 }

然后我们再看看使用yield return返回集合操作:

 class Program
 {
 static private List<int> _numArray; //用来保存1-100 这100个整数

 Program() //构造函数。我们可以通过这个构造函数往待测试集合中存入1-100这100个测试数据
 {
  _numArray = new List<int>(); //给集合变量开始在堆内存上开内存,并且把内存首地址交给这个_numArray变量

  for (int i = 1; i <= 100; i++)
  {
  _numArray.Add(i); //把1到100保存在集合当中方便操作
  }
 }

 static void Main(string[] args)
 {
  new Program();

  TestMethod();

 }

 //测试求1到100之间的全部偶数
 static public void TestMethod()
 {
  foreach (var item in GetAllEvenNumber())
  {
  Console.WriteLine(item); //输出偶数测试
  }
 } 

 //使用Yield Return情况下的方法
 static IEnumerable<int> GetAllEvenNumber()
 {

  foreach (int num in _numArray)
  {
  if (num % 2 == 0) //判断是不是偶数
  {
   yield return num; //返回当前偶数

  }
  }
  yield break; //当前集合已经遍历完毕,我们就跳出当前函数,其实你不加也可以
  //这个作用就是提前结束当前函数,就是说这个函数运行完毕了。
 }

 }

与平常return比较

上面我们看到了yield return 的使用方法,那么这个与return返回集合有什么区别呢?我们看下面一个案例来进行分析:

我们首先先看通过returun返回集合的一个案例:

 class Program
 {
 static void Main(string[] args)
 {
  foreach (var item in GetNums())
  {
  Console.WriteLine($" common return:{item}");
  }
 } 

 /// <summary>
 /// 平常return 返回集合
 /// </summary>
 /// <returns></returns>
 public static IEnumerable<int> GetNums()
 {
  var listNum = new List<int>();
  for (int i = 0; i < 10; i++)
  {
  Console.WriteLine($"yield return:{i}");
  listNum.Add(i);
  }
  return listNum;
 }
 }

通过代码的运行结果,我们可以看到这里返回的结果 yield return 和comment return是分成两边的。先执行完一个然后开始执行另外一个。不干涉。

我们接着看下使用yield return返回集合:

 class Program
 {
 static void Main(string[] args)
 {
  foreach (var item in GetNumsYield())
  {
  Console.WriteLine($" common return:{item}");
  }
 }

 /// <summary>
 /// 通过yield return 返回集合
 /// </summary>
 /// <returns></returns>
 public static IEnumerable<int> GetNumsYield()
 {
  for (int i = 0; i < 10; i++)
  {
  Console.WriteLine($"yield return:{i}");
  yield return i;
  }
 }
 }

我们看这个运行结果,这里yield return 和comment return 的输出完全交替了。这里说明是一次调用就返回了一个元素。

通过上面的案例我们可以发现,yield return 并不是等所有执行完了才一次性返回的。而是调用一次就返回一次结果的元素。这也就是按需供给。

解析定义类

我们已经大致了解了yield 的用法和它与平常的返回的区别。我们可以继续查看其运行原理。我们首先看这么一个案例(在0-10中随机返回五个数字):

我们通过SharpLab反编译其代码,我们进行查看发现yield具体详细实现:

我们看到yield内部含有一个迭代器。这样去实现的迭代遍历。同时包含_state字段、用来存储上一次的记录。_current包含当前的值、也通过_initialThreadId获取当前线程id。其中主要的方法是迭代器方法MoveNext()。我们根据反编译结果来实现一个与yiled相似的类:

 /// <summary>
 /// 解析yield并定义相似类
 /// </summary>
 public sealed class GetRandomNumbersClass : IEnumerable<int>, IEnumerable, IEnumerator<int>, IDisposable, IEnumerator
 {
  public static Random r = new Random();

  /// <summary>
  /// 状态
  /// </summary>
  private int _state;

  /// <summary>
  ///储存当前值
  /// </summary>
  private int _current;

  /// <summary>
  /// 线程id
  /// </summary>
  private int _initialThreadId;

  /// <summary>
  /// 集合元素数量
  /// </summary>
  private int count;

  /// <summary>
  /// 集合元素数量
  /// </summary>
  public int _count;

  /// <summary>
  /// 当前指针
  /// </summary>
  private int i;

  int IEnumerator<int>.Current
  {
   [DebuggerHidden]
   get
   {
    return _current;
   }
  }

  object IEnumerator.Current
  {
   [DebuggerHidden]
   get
   {
    return _current;
   }
  }

  [DebuggerHidden]
  public GetRandomNumbersClass(int state)
  {
   this._state = state;
   _initialThreadId = Environment.CurrentManagedThreadId;
  }

  [DebuggerHidden]
  void IDisposable.Dispose()
  {
  }

  private bool MoveNext()
  {
   switch (_state)
   {
    default:
     return false;
    case 0:
     _state = -1;
     i = 0;
     break;
    case 1:
     _state = -1;
     i++;
     break;
   }
   if (i < count)
   {
    _current = r.Next(10);
    _state = 1;
    return true;
   }
   return false;
  }

  bool IEnumerator.MoveNext()
  {
   //ILSpy generated this explicit interface implementation from .override directive in MoveNext
   return this.MoveNext();
  }

  [DebuggerHidden]
  void IEnumerator.Reset()
  {
   throw new NotSupportedException();
  }

  [DebuggerHidden]
  public IEnumerator<int> GetEnumerator()
  {
   GetRandomNumbersClass _getRandom;
   if (_state == -2 && _initialThreadId == Environment.CurrentManagedThreadId)
   {
    _state = 0;
    _getRandom = this;
   }
   else
   {
    _getRandom = new GetRandomNumbersClass(0);
   }
   _getRandom.count = _count;
   return _getRandom;
  }

  [DebuggerHidden]
  IEnumerator IEnumerable.GetEnumerator()
  {
   return GetEnumerator();
  }

  [IteratorStateMachine(typeof(GetRandomNumbersClass))]
  private static IEnumerable<int> GetList(int count)
  {
   GetRandomNumbersClass getRandomNumbersClass = new GetRandomNumbersClass(-2);
   getRandomNumbersClass._count = count;
   return getRandomNumbersClass;
  }
  private static void Main(string[] args)
  {
   IEnumerator<int> enumerator = GetList(5).GetEnumerator();
   try
   {
    foreach (int item in GetList(5))
     Console.WriteLine(item);
    //while (enumerator.MoveNext())
    //{
    // int current = enumerator.Current;
    // Console.WriteLine(current);
    //}
   }
   finally
   {
    if (enumerator != null)
    {
     enumerator.Dispose();
    }
   }
   Console.ReadKey();
  }
 }

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。

(0)

相关推荐

  • C#中的yield关键字的使用方法介绍

    yield不能单独放在try-catch块中,如果try中有yield那么,这个try块后面不许跟着finally块:也不能出现在匿名方法中,所以,看起来yield似乎并不常用,但是也不是不用.我前面有一个关于迭代器的例子<C#中的迭代器基础>中就用到了.可以参考一下那个例子,但是这里要再说的一点是我后来看到的,yield是跟return一起使用的,形式为yield return xxx,一般来说单独的return在每个方法中只能存在一个.而yield则不同的是,可以出现连续多个.迭代器,是一

  • C#使用yield关键字构建迭代器详解

    以前,如果我们希望构建支持foreach枚举的自定义集合,只能实现IEnumerable接口(可能还有IEnumerator()),返回值还必须是IEnumerator类型,除此之外还可以通过迭代器来使用构建foreach循环的类型,详细见下链接. 代码 public class Car { //内部状态数据 public int CurentSpeed; public int MaxSpeed; public string name; //汽车能不能用 private bool carIsde

  • C#使用yield关键字让自定义集合实现foreach遍历的方法

    foreach遍历是C#常见的功能,而本文通过实例形式展现了C#使用yield关键字让自定义集合实现foreach遍历的方法.具体步骤如下: 一般来说当我们创建自定义集合的时候为了让其能支持foreach遍历,就只能让其实现IEnumerable接口(可能还要实现IEnumerator接口) 但是我们也可以通过使用yield关键字构建的迭代器方法来实现foreach的遍历,且自定义的集合不用实现IEnumerable接口 注意:虽然不用实现IEnumerable接口 ,但是迭代器的方法必须命名为

  • C# yield关键字详解

    对于yield关键字我们首先看一下msdn的解释: 如果你在语句中使用 yield 关键字,则意味着它在其中出现的方法.运算符或 get 访问器是迭代器. 通过使用 yield 定义迭代器,可在实现自定义集合类型的 IEnumerable和 IEnumerator模式时无需其他显式类(保留枚举状态的类,有关示例,请参阅 IEnumerator<T>). yield是一个语法糖 看msdn 的解释总是让人感觉生硬难懂.其实yield关键字很好理解.首先我们对于性质有个了解.yield是一个语法糖

  • 关于C#中yield关键字的深入解析

    前言 前段时间了解到yield关键字,一直觉得还不错.今天给大家分享一下yield关键字的用法.yield return 返回集合不是一次性返回所有集合元素,而是一次调用返回一个元素.具体如何使用yield return 返回集合呢?我们一起往下面看吧. yield使用介绍 yield return 和yield break: 我们看下平常循环返回集合的使用操作(返回1-100中的偶数): class Program { static private List<int> _numArray;

  • 解析c# yield关键字

    1.yield实现的功能 yield return: 先看下面的代码,通过yield return实现了类似用foreach遍历数组的功能,说明yield return也是用来实现迭代器的功能的. using static System.Console; using System.Collections.Generic; class Program { //一个返回类型为IEnumerable<int>,其中包含三个yield return public static IEnumerable&

  • 深入理解PHP中的static和yield关键字

    前言 本文主要给大家介绍了关于PHP中static和yield关键字的相关内容,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 先来说说 static 关键字.本篇只讲静态方法的使用与后期绑定的知识点. static 什么时候用来修饰方法 static 关键字大家都知道是用来修饰方法与属性的. 那么大家在项目中会在哪些场景下使用它? 我遇到过几个项目,要求所有的方法全部 static 化,当然控制器方法不能这么干.原因之一就是:静态方法执行效率高?那么我们基于此来分析一下. 首

  • 彻底理解Python中的yield关键字

    阅读别人的python源码时碰到了这个yield这个关键字,各种搜索终于搞懂了,在此做一下总结: 通常的for...in...循环中,in后面是一个数组,这个数组就是一个可迭代对象,类似的还有链表,字符串,文件.它可以是mylist = [1, 2, 3],也可以是mylist = [x*x for x in range(3)].它的缺陷是所有数据都在内存中,如果有海量数据的话将会非常耗内存. 生成器是可以迭代的,但只可以读取它一次.因为用的时候才生成.比如 mygenerator = (x*x

  • 深入浅析Python中的yield关键字

    前言 python中有一个非常有用的语法叫做生成器,所利用到的关键字就是yield.有效利用生成器这个工具可以有效地节约系统资源,避免不必要的内存占用. 一段代码 def fun(): for i in range(20): x=yield i print('good',x) if __name__ == '__main__': a=fun() a.__next__() x=a.send(5) print(x) 这段代码很短,但是诠释了yield关键字的核心用法,即逐个生成.在这里获取了两个生成

  • 通过实例解析c# yield关键字使用方法

    1.yield实现的功能 yield return: 先看下面的代码,通过yield return实现了类似用foreach遍历数组的功能,说明yield return也是用来实现迭代器的功能的. using static System.Console; using System.Collections.Generic; class Program { //一个返回类型为IEnumerable<int>,其中包含三个yield return public static IEnumerable&

  • Java类中this关键字与static关键字的用法解析

    目录 前言 1:修饰属性,表示调用类中的成员变量. 2:this修饰方法 3:this表示当前对象的引用 前言 今天给大家总结介绍一下Java类中this关键字和static关键字的用法. this关键字用法: this.属性可以调用类中的成员变量 this()可以调用类中的构造方法 1:修饰属性,表示调用类中的成员变量. 代码示例: public class Student { public String name; public int age; public String school;

  • javascript中new关键字详解

    和其他高级语言一样javascript中也有new关键字,我们以前认知的new是用来创建一个类的实例对象,但在js中万物皆是对象,为何还要new关键字呢,其实js中new关键字不是用来创建一个类的实例对象,而是用于继承. 接下来,本文将带你一起来探索JS中new的奥秘... function Animal(name){ this.name = name; } Animal.color = "black"; Animal.prototype.say = function(){ conso

  • JavaScript中this关键字使用方法详解

    在面向对象编程语言中,对于this关键字我们是非常熟悉的.比如C++.C#和Java等都提供了这个关键字,虽然在开始学习的时候觉得比较难,但只要理解了,用起来是非常方便和意义确定的.JavaScript也提供了这个this关键字,不过用起来就比经典OO语言中要"混乱"的多了. 下面就来看看,在JavaScript中各种this的使用方法有什么混乱之处? 1.在HTML元素事件属性中inline方式使用this关键字: <div onclick="  // 可以在里面使用

随机推荐