天天看點

多角度讓你徹底明白yield文法糖的用法和原理及在C#函數式程式設計中的作用

如果大家讀過dapper源碼,你會發現這内部有很多方法都用到了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卻在方法體内沒有看到任何實作這個接口的子類,是以第一感覺就是這個yield不簡單,既然代碼可以跑,那底層肯定幫你實作了一個繼承IEnumerable接口的子類,你說對吧?

2. msdn解釋

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

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

沒用過yield之前,看這句話肯定是一頭霧水,隻有在業務開發中踩過坑,才能體會到yield所帶來的快感。

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> 無緣無故的多了一個叫做<GetList>d__1 類

好奇心驅使着我看一下這個類到底都有些什麼?由于IL代碼太多,我做一下精簡,從下面的IL代碼中可以發現,果然是實作了IEnumerable接口,如果你了解設計模式中的疊代器模式,那這裡的MoveNext,Current是不是非常熟悉?😄😄😄

.class nested private auto ansi sealed beforefieldinit '<GetList>d__1'
	extends [mscorlib]System.Object
	implements 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 virtual 
		instance bool MoveNext () cil managed 
	{
		...
	} // end of method '<GetList>d__1'::MoveNext

	.method private final hidebysig specialname newslot virtual 
		instance 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 virtual 
		instance object System.Collections.IEnumerator.get_Current () cil managed 
	{
		...
	} // end of method '<GetList>d__1'::System.Collections.IEnumerator.get_Current

	.method private final hidebysig newslot virtual 
		instance 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> GetList方法展現在會變成啥樣?

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

           

可以看到這地方做了一個new ConsoleApp2.Program/'d__1'操作,然後進行了<>3__nums=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到底有什麼好處

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

1. 現階段還不清楚用什麼集合來承載這些資料

這話什麼意思?同樣的一堆集合資料,你可以用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方法就是實作了這麼一種操作,最後使用ToList一次性輸出,由于沒有中間商,是以靈活性和性能可想而知。

三:總結

函數式程式設計将會是以後的主流方向,C#中幾乎所有的新特性都是為了給函數式程式設計提供便利性,而這個yield就是C#函數式程式設計中的一個基柱,你還可以補看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;
            }
        }

           

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