当处理类似的事情时List<string>
你可以写以下内容:
list.ForEach(x => Console.WriteLine(x));
或者您可以使用方法组来执行相同的操作:
list.ForEach(Console.WriteLine);
我更喜欢第二行代码,因为它对我来说看起来更干净,但是这样做有什么好处吗?
好吧,让我们看看会发生什么。
static void MethodGroup()
{
new List<string>().ForEach(Console.WriteLine);
}
static void LambdaExpression()
{
new List<string>().ForEach(x => Console.WriteLine(x));
}
这将被编译成以下 IL。
.method private hidebysig static void MethodGroup() cil managed
{
.maxstack 8
L_0000: newobj instance void [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
L_0005: ldnull
L_0006: ldftn void [mscorlib]System.Console::WriteLine(string)
L_000c: newobj instance void [mscorlib]System.Action`1<string>::.ctor(object, native int)
L_0011: call instance void [mscorlib]System.Collections.Generic.List`1<string>::ForEach(class [mscorlib]System.Action`1<!0>)
L_0016: ret
}
.method private hidebysig static void LambdaExpression() cil managed
{
.maxstack 8
L_0000: newobj instance void [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
L_0005: ldsfld class [mscorlib]System.Action`1<string> Sandbox.Program::CS$<>9__CachedAnonymousMethodDelegate1
L_000a: brtrue.s L_001d
L_000c: ldnull
L_000d: ldftn void Sandbox.Program::<LambdaExpression>b__0(string)
L_0013: newobj instance void [mscorlib]System.Action`1<string>::.ctor(object, native int)
L_0018: stsfld class [mscorlib]System.Action`1<string> Sandbox.Program::CS$<>9__CachedAnonymousMethodDelegate1
L_001d: ldsfld class [mscorlib]System.Action`1<string> Sandbox.Program::CS$<>9__CachedAnonymousMethodDelegate1
L_0022: call instance void [mscorlib]System.Collections.Generic.List`1<string>::ForEach(class [mscorlib]System.Action`1<!0>)
L_0027: ret
}
注意方法组方法如何创建Action<T>
委托一次使用,并且 lambda 表达式方法创建一个隐藏的匿名委托字段,并在必要时对其进行内联初始化。注意brtrue
指令于IL_000a
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)