Vâng, hãy xem và xem điều gì sẽ xảy ra.
static void MethodGroup()
{
new List<string>().ForEach(Console.WriteLine);
}
static void LambdaExpression()
{
new List<string>().ForEach(x => Console.WriteLine(x));
}
Điều này được biên dịch thành IL sau đây.
.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
}
Chú ý cách tiếp cận nhóm phương pháp tạo ra một đại biểu Action<T>
cho một thời gian sử dụng và các phương pháp biểu thức lambda tạo ra một lĩnh vực đại biểu vô danh ẩn và làm một khởi inline của nó nếu cần thiết. Thông báo hướng dẫn brtrue
tại IL_000a
.
Nguồn
2010-10-01 18:56:59
Vâng, ReSharper khuyến cáo các phiên bản thứ hai. Vì vậy, nó phải là một trong những quyền ... –
"Một người thông minh hơn nói rằng đúng" không thực sự là một lời giải thích của * TẠI SAO *. Nó có thể đúng. Nó có thể là câu trả lời tốt nhất. Nhưng điều đó không trả lời câu hỏi "tại sao". – WernerCD