在那里,如果可使用C#方法组什么好处? [英] Are there any benefits to using a C# method group if available?
问题描述
当使用像一个处理列表与LT;串>
你可以写:
When dealing with something like a List<string>
you can write the following:
list.ForEach(x => Console.WriteLine(x));
或者你可以使用的方法组完成相同的操作:
or you can use a method group to do the same operation:
list.ForEach(Console.WriteLine);
我preFER code的第二行,因为它看起来更清洁的我,但有什么好处呢?
I prefer the second line of code because it looks cleaner to me, but are there any benefits to this?
推荐答案
好吧,让我们来看看,看看会发生什么。
Well, lets take a look and see what happens.
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
}
注意方法组的做法是如何创建一个动作&LT; T&GT;
委托一次性使用和拉姆达前pression方法创建一个隐藏的匿名委托外地和不它内联初始化,如果必要的。在 IL_000a
的通知 brtrue
指令。
Notice how the method group approach creates an Action<T>
delegate for one time use and the lambda expression approach creates a hidden anonymous delegate field and does an inline initialization of it if necessary. Notice brtrue
instruction at IL_000a
.
这篇关于在那里,如果可使用C#方法组什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!