多角度让你彻底明白yield语法糖的用法和原理及在C#函数式编程中的作用
如果大家讀過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#函数式编程中的作用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .NET Core技术研究-主机
- 下一篇: 哪种开源许可证最适合商业化?