联博统计_多角度让你彻底明了yield语法糖的用法和原理及在C#函数式编程中的作用
发表时间:2021-01-03 浏览量:87
多角度让你彻底明了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 style="box-sizing: border-box;"> 无缘无故的多了一个叫做\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 style="box-sizing: border-box;"> 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/'d1'操作,然后举行了<>3nums=0,最后再把这个迭代类返回出来,这就注释了为什么你的GetList可以是IEnumerable而不报错。
,,www.weqvip.com采用以太坊区块链高度哈希值作为统计数据,联博以太坊统计数据开源、公平、无任何作弊可能性。联博统计免费提供API接口,支持多语言接入。
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;
}
}
好了,本篇就说到这里,希望对你有辅助。
0
珍藏