日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

多角度让你彻底明白yield语法糖的用法和原理及在C#函数式编程中的作用

發(fā)布時間:2023/12/4 C# 44 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多角度让你彻底明白yield语法糖的用法和原理及在C#函数式编程中的作用 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

如果大家讀過dapper源碼,你會發(fā)現(xiàn)這內部有很多方法都用到了yield關鍵詞,那yield到底是用來干嘛的,能不能拿掉,拿掉與不拿掉有多大的差別,首先上一段dapper中精簡后的Query方法,先讓大家眼見為實。

private static IEnumerable<T> QueryImpl<T>(this IDbConnection cnn, CommandDefinition command, Type effectiveType){object param = command.Parameters;var identity = new Identity(command.CommandText, command.CommandType, cnn, effectiveType, param?.GetType());var info = GetCacheInfo(identity, param, command.AddToCache);IDbCommand cmd = null;IDataReader reader = null;bool wasClosed = cnn.State == ConnectionState.Closed;try{while (reader.Read()){object val = func(reader);if (val == null || val is T){yield return (T)val;}else{yield return (T)Convert.ChangeType(val, convertToType, CultureInfo.InvariantCulture);}}}}

一:yield探究

1. 骨架代碼猜想

骨架代碼其實很簡單,方法的返回值是IEnumerable,然后return被yield開了光,讓人困惑的地方就是既然方法的返回值是IEnumerable卻在方法體內沒有看到任何實現(xiàn)這個接口的子類,所以第一感覺就是這個yield不簡單,既然代碼可以跑,那底層肯定幫你實現(xiàn)了一個繼承IEnumerable接口的子類,你說對吧?

2. msdn解釋

有自己的猜想還不行,還得相信權威,看msdn的解釋:https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/yield


如果你在語句中使用 yield 上下文關鍵字,則意味著它在其中出現(xiàn)的方法、運算符或 get 訪問器是迭代器。通過使用 yield 定義迭代器,可在實現(xiàn)自定義集合類型的 IEnumerator?和 IEnumerable 模式時無需其他顯式類(保留枚舉狀態(tài)的類,有關示例,請參閱 IEnumerator)。


沒用過yield之前,看這句話肯定是一頭霧水,只有在業(yè)務開發(fā)中踩過坑,才能體會到y(tǒng)ield所帶來的快感。

3. 從IL入手

為了方便探究原理,我來寫一個不能再簡單的例子。

public static void Main(string[] args){var list = GetList(new int[] { 1, 2, 3, 4, 5 });}public static IEnumerable<int> GetList(int[] nums){foreach (var num in nums){yield return num;}}

對,就是這么簡單,接下來用ILSpy反編譯打開這其中的神秘面紗。

從截圖中看最讓人好奇的有兩點。

<1 style="box-sizing: border-box;"> 無緣無故的多了一個叫做\d__1 類

好奇心驅使著我看一下這個類到底都有些什么?由于IL代碼太多,我做一下精簡,從下面的IL代碼中可以發(fā)現(xiàn),果然是實現(xiàn)了IEnumerable接口,如果你了解設計模式中的迭代器模式,那這里的MoveNext,Current是不是非常熟悉?????????????

.class nested private auto ansi sealed beforefieldinit '<GetList>d__1'extends [mscorlib]System.Objectimplements class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>,[mscorlib]System.Collections.IEnumerable,class [mscorlib]System.Collections.Generic.IEnumerator`1<int32>,[mscorlib]System.IDisposable,[mscorlib]System.Collections.IEnumerator {.method private final hidebysig newslot virtualinstance bool MoveNext () cil managed{...} // end of method '<GetList>d__1'::MoveNext.method private final hidebysig specialname newslot virtualinstance int32 'System.Collections.Generic.IEnumerator<System.Int32>.get_Current' () cil managed{...} // end of method '<GetList>d__1'::'System.Collections.Generic.IEnumerator<System.Int32>.get_Current'.method private final hidebysig specialname newslot virtualinstance object System.Collections.IEnumerator.get_Current () cil managed{...} // end of method '<GetList>d__1'::System.Collections.IEnumerator.get_Current.method private final hidebysig newslot virtualinstance class [mscorlib]System.Collections.Generic.IEnumerator`1<int32> 'System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator' () cil managed{...} // end of method '<GetList>d__1'::'System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator'} // end of class <GetList>d__1

<2 style="box-sizing: border-box;"> GetList方法體現(xiàn)在會變成啥樣?

.method public hidebysig staticclass [mscorlib]System.Collections.Generic.IEnumerable`1<int32> GetList (int32[] nums) cil managed {// (no C# code)IL_0000: ldc.i4.s -2IL_0002: newobj instance void ConsoleApp2.Program/'<GetList>d__1'::.ctor(int32)IL_0007: dupIL_0008: ldarg.0IL_0009: stfld int32[] ConsoleApp2.Program/'<GetList>d__1'::'<>3__nums'IL_000e: ret } // end of method Program::GetList

可以看到這地方做了一個new ConsoleApp2.Program/'d1'操作,然后進行了<>3nums=0,最后再把這個迭代類返回出來,這就解釋了為什么你的GetList可以是IEnumerable而不報錯。

4. 打回C#代碼

你可能會說,你說了這么多有啥用?IL代碼我也看不懂,如果能回寫成C#代碼那就????????了,還好回寫成C#代碼不算太難。。。

namespace ConsoleApp2 {class GetListEnumerable : IEnumerable<int>, IEnumerator<int>{private int state;private int current;private int threadID;public int[] nums;public int[] s1_nums;public int s2;public int num53;public GetListEnumerable(int state){this.state = state;this.threadID = Environment.CurrentManagedThreadId;}public int Current => current;public IEnumerator<int> GetEnumerator(){GetListEnumerable rangeEnumerable;if (state == -2 && threadID == Environment.CurrentManagedThreadId){state = 0;rangeEnumerable = this;}else{rangeEnumerable = new GetListEnumerable(0);}rangeEnumerable.nums = nums;return rangeEnumerable;}public bool MoveNext(){switch (state){case 0:state = -1;s1_nums = nums;s2 = 0;num53 = s1_nums[s2];current = num53;state = 1;return true;case 1:state = -1;s2++;if (s2 < s1_nums.Length){num53 = s1_nums[s2];current = num53;state = 1;return true;}s1_nums = null;return false;}return false;}object IEnumerator.Current => Current;public void Dispose() { }public void Reset() { }IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); }} }

接下來GetList就可以是另一種寫法了,做一個new GetListEnumerable 即可。

到目前為止,我覺得這個yield你應該徹底的懂了,否則就是我的失敗(┬_┬)...

二:yield到底有什么好處

以我自己幾年開發(fā)經(jīng)驗(不想把自己說的太老(┬_┬))來看,有如下兩點好處。

1. 現(xiàn)階段還不清楚用什么集合來承載這些數(shù)據(jù)

這話什么意思?同樣的一堆集合數(shù)據(jù),你可以用List承載,你也可以用SortList,HashSet甚至還可以用Dictionary承載,對吧,你當時定義方法的時候返回值那里是一定要先定義好接收集合,但這個接收集合真的合適嗎?你當時也是不知道的。如果你還不明白,我舉個例子:

public static class Program{public static void Main(string[] args){//哈哈,我最后想要HashSet。。。因為我要做高效的集合去重var hashSet1 = new HashSet<int>(GetList(new int[] { 1, 2, 3, 4, 5 }));var hashSet2 = new HashSet<int>(GetList2(new int[] { 1, 2, 3, 4, 5 }));}//編碼階段就預先決定了用List<int>承載public static List<int> GetList(int[] nums){return nums.Where(num => num % 2 == 0).ToList();}//編碼階段還沒想好用什么集合承載,有可能是HashSet,SortList,鬼知道呢?public static IEnumerable<int> GetList2(int[] nums){foreach (var num in nums){if (num % 2 == 0) yield return num;}}}

先看代碼中的注釋,從上面例子中可以看到我真正想要的是HashSet,而此時hashSet2 比 hashSet1 少了一個中轉過程,無形中這就大大提高了代碼性能,對不對?

  • hashSet1 其實是 int[] -> List -> HashSet 的過程。

  • hashSet2 其實是 int[] -> HashSet 的過程。

2. 可以讓我無限制的疊加篩選塑形條件

這個又是什么意思呢?有時候方法調用棧是特別深的,你無法對一個集合在最底層進行整體一次性篩選,而是在每個方法中實行追加式篩選塑性,請看如下示例代碼。

public static class Program{public static void Main(string[] args){var nums = M1(true).ToList();}public static IEnumerable<int> M1(bool desc){return desc ? M2(2).OrderByDescending(m => m) : M2(2).OrderBy(m => m);}public static IEnumerable<int> M2(int mod){return M3(0, 10).Where(m => m % mod == 0);}public static IEnumerable<int> M3(int start, int end){var nums = new int[] { 1, 2, 3, 4, 5 };return nums.Where(i => i > start && i < end);}}

上面的M1,M2,M3方法就是實現(xiàn)了這么一種操作,最后使用ToList一次性輸出,由于沒有中間商,所以靈活性和性能可想而知。

三:總結

函數(shù)式編程將會是以后的主流方向,C#中幾乎所有的新特性都是為了給函數(shù)式編程提供便利性,而這個yield就是C#函數(shù)式編程中的一個基柱,你還可以補看Enumerable中的各種擴展方法增加一下我的說法可信度。

static IEnumerable<TSource> TakeWhileIterator<TSource>(IEnumerable<TSource> source, Func<TSource, bool> predicate) {foreach (TSource element in source) {if (!predicate(element)) break;yield return element;}}static IEnumerable<TSource> WhereIterator<TSource>(IEnumerable<TSource> source, Func<TSource, int, bool> predicate) {int index = -1;foreach (TSource element in source) {checked { index++; }if (predicate(element, index)) yield return element;}}

好了,本篇就說到這里,希望對你有幫助。

總結

以上是生活随笔為你收集整理的多角度让你彻底明白yield语法糖的用法和原理及在C#函数式编程中的作用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內容還不錯,歡迎將生活随笔推薦給好友。

主站蜘蛛池模板: 欧美三级在线看 | 成人免费视频一区二区三区 | 欧美视频网站 | 亚洲孕交 | 一区二区视频 | 久操视频在线观看 | 激情视频一区 | 成人精品 | 国产精品人人做人人爽 | 国产人成| 亚洲欧美成人综合 | 日本久久视频 | 日韩在线小视频 | 国产一伦一伦一伦 | 精品无码一区二区三区的天堂 | 天天躁日日躁狠狠躁欧美 | 亚洲欧美影院 | 午夜爽爽爽 | 夫妻性生活黄色片 | 国产美女精品 | 国产精品99一区二区三区 | 妞干网这里只有精品 | 黄网站免费视频 | 成人作爱视频 | 激情久久久 | 中文字幕精品一区二 | 国产在线视频网站 | 亚洲精品久久一区二区三区777 | 91精产国品一二三区在线观看 | 日本一区二区三区精品视频 | 免费三级网站 | 亚洲av色香蕉一区二区三区 | 亚洲色图网友自拍 | 亚洲制服丝袜一区 | 国内精品视频在线播放 | 亚洲乱熟女一区二区三区小说 | 国产对白视频 | 男人天堂色 | 黄色片免费观看 | xxxxxhd亚洲人hd | 自拍亚洲综合 | 欧美性xxxx | 亚洲av不卡一区二区 | 欧美一区免费看 | 神马午夜场 | 少妇太爽了 | 欧日韩在线| 国产另类av| 日韩免费专区 | 天海翼一二三区 | 给我免费观看片在线电影的 | 人人插人人射 | 污片网站 | 亚洲黄色片免费看 | 国产另类在线 | 国产99久久久国产精品免费看 | 91在线无精精品白丝 | 丁香六月天婷婷 | 日本免费一区二区视频 | 国产男女爽爽爽 | 亚洲v国产 | 国产精品久久久久久免费免熟 | 欧美少妇在线 | 成人黄色在线免费观看 | 波多野结衣视频在线 | 激情五月开心婷婷 | 精品国产av无码一区二区三区 | 一级片免费在线 | 久久久国产一区二区三区 | 婷婷五月综合久久中文字幕 | 99精品视频在线免费观看 | 在线观看日韩欧美 | 亚洲不卡在线 | 先锋影音制服丝袜 | 精产国品一二三区 | 午夜影院 | 久色福利 | 日韩手机在线观看 | 国产特级毛片aaaaaa | 伊人久久中文字幕 | 国产一区二区三区日韩 | 国产伊人网 | 色悠久久综合 | 欧美在线一区二区三区 | 国产一区91| 国产夫妻露脸 | brazzers精品成人一区 | 成人免费视频网站在线看 | 日韩国产网站 | 国产视频久久久久久 | 波多野结衣一区二区三区免费视频 | 亚洲美女一级片 | 亚洲三级电影网站 | av一本二本 | av手机网站 | 欧美激情一区二区三区免费观看 | 一级黄色网| 亚洲欧美综合自拍 | 色噜噜影院 |