国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

C#中yieldreturn用法分析

2019-11-14 13:45:44
字體:
來源:轉載
供稿:網友

說明:yield關鍵字用于遍歷循環中,yield return用于返回IEnumerable<T>,yield break用于終止循環遍歷。

以下對比了使用yield return與不使用yield return的情況,直接上代碼:

using System;using System.Collections.Generic;namespace ConsoleApp{    class PRogram    {        static void Main(string[] args)        {            Console.WriteLine("不使用 yield return 方式的結果");            foreach (var item in WithoutYield())            {                Console.WriteLine(item);            }            Console.WriteLine("使用 yield return 方式的結果");            foreach (var item in WithYield())            {                Console.WriteLine(item);            }            Console.ReadLine();        }        /// <summary>        /// 不使用 yield return        /// </summary>        /// <returns></returns>        static IEnumerable<int> WithoutYield()        {            List<int> result = new List<int>();            foreach (int i in GetData())            {                if (i > 2)                {                    result.Add(i);                }            }            return result;        }        /// <summary>        /// 使用 yield return        /// </summary>        /// <returns></returns>        static IEnumerable<int> WithYield()        {            foreach (int i in GetData())            {                if (i > 2)                {                    yield return i;                }            }            yield break;            Console.WriteLine("這里的代碼不執行");        }        /// <summary>        /// 獲取數據        /// </summary>        /// <returns></returns>        static List<int> GetData()        {            return new List<int>() { 1, 2, 3, 4 };        }    }}

輸出結果如下:

總結:

通過調試發現:兩種方法的輸出結果是一樣的,但實際的運作過程是不同的。

第一種方法,是把結果集全部加載到內存中再遍歷;

第二種方法,遍歷每調用一次,yield return就返回一個值;

因此,當希望獲取一個IEnumerable<T>類型的集合,而不想把數據一次性加載到內存,就可以考慮使用yield return的方式去實現;


發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 汝阳县| 讷河市| 纳雍县| 宁蒗| 万州区| 台南县| 宁晋县| 台南县| 东安县| 鄂伦春自治旗| 阿图什市| 平武县| 黎城县| 江津市| 阆中市| 平遥县| 寿阳县| 饶阳县| 余姚市| 滕州市| 屏边| 岑巩县| 桂林市| 涟源市| 九寨沟县| 达拉特旗| 万源市| 长宁区| 浦东新区| 阳江市| 九江县| 尚志市| 余庆县| 鹿邑县| 苗栗市| 嘉定区| 报价| 三河市| 石屏县| 三明市| 兴宁市|