Difference between lambda expression and method group

那年仲夏 提交于 2020-01-09 07:42:08

问题


What's the difference between

Class1.Method1<Guid, BECustomer>("cId", Facade.Customers.GetSingle);

and

Class1.Method1<Guid, BECustomer>("cId", x => Facade.Customers.GetSingle(x));

?

Resharper suggests to use the first expression.


回答1:


There is no difference in regards to the result. However, the second one creates an additional redirection: The code will first call your anonymous method the takes one parameter named x and that in turn calls Facade.Customers.GetSingle with that parameter. This redirection has no benefit at all, that's why ReSharper tells you to use the first alternative.




回答2:


Behind the scenes, the compiler generates a lot more code if you use the lambda expression. With the method group, it just makes a new delegate pointing to that method:

L_0001: ldstr "cId"
L_0006: ldnull 
L_0007: ldftn void Facade/Customers::GetSingle(valuetype [mscorlib]System.Guid)
L_000d: newobj instance void [mscorlib]System.Action`1<valuetype [mscorlib]System.Guid>::.ctor(object, native int)
L_0012: call void Class1::Method1<valuetype [mscorlib]System.Guid, class BECustomer>(string, class [mscorlib]System.Action`1<!!0>)

With the lambda expression, an anonymous method is created on the class (<Test>b__0 on L_0025) and the delegate references that instead:

L_0018: ldstr "cId"
L_001d: ldsfld class [mscorlib]System.Action`1<valuetype [mscorlib]System.Guid> Class1::CS$<>9__CachedAnonymousMethodDelegate1
L_0022: brtrue.s L_0037
L_0024: ldnull 
L_0025: ldftn void Class1::<Test>b__0(valuetype [mscorlib]System.Guid)
L_002b: newobj instance void [mscorlib]System.Action`1<valuetype [mscorlib]System.Guid>::.ctor(object, native int)
L_0030: stsfld class [mscorlib]System.Action`1<valuetype [mscorlib]System.Guid> Class1::CS$<>9__CachedAnonymousMethodDelegate1
L_0035: br.s L_0037
L_0037: ldsfld class [mscorlib]System.Action`1<valuetype [mscorlib]System.Guid> Class1::CS$<>9__CachedAnonymousMethodDelegate1
L_003c: call void Class1::Method1<valuetype [mscorlib]System.Guid, class BECustomer>(string, class [mscorlib]System.Action`1<!!0>)



回答3:


Where your Method1<Guid, BECustomer> accepts a Func<Guid, BECustomer> argument, Func<Guid, BECustomer> is synonymous with:

public delegate BECustomer Func(Guid arg);

In fact, all a Func is is a generic delegate:

public delegate TResult Func<T, TResult>(T arg);

The compiler can analyse your code and determine that your Func<Guid, BECustomer> is compatible with the method group for Facade.Customers.GetSingle because the method signature matches the delegate signature.

This is syntactic sugar and is another example of the compiler doing the grunt work for you.



来源:https://stackoverflow.com/questions/6662532/difference-between-lambda-expression-and-method-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!