c# - Working with methods that return anonymous methods -
if have class this:
public class someclass { public action<string> someaction { get; set; } public someclass() { someaction = getsomeanonymousmethod(); } private action<string> getsomeanonymousmethod() { homecoming (text) => { console.writeline(text); }; } } what happens when create new instance of someclass? impression constructor calls getsomeanonymousmethod(), returns new delegate instance (that contains reference compiler-generated backing method anonymous method), , assigns someaction property.
can confirm, or more sinister happening?
well, that's nearly happens. in particular case, lambda look (it's not anonymous method, picky) doesn't need state, generated method can static, , delegate reference can cached. "new delegate instance" part may not correct.
so it's more - @ to the lowest degree when compiled ms compiler:
public class someclass { private static action<string> cachedaction; public action<string> someaction { get; set; } public someclass() { someaction = getsomeanonymousmethod(); } private action<string> getsomeanonymousmethod() { action<string> action = cachedaction; if (action == null) { action = anonymousmethodimplementation; cachedaction = action; } homecoming action; } private static void anonymousmethodimplementation(string text) { console.writeline(text); } } you don't need worry details of - , it's implementation detail... bit of optimization. if want know what's going on, that's closer reality.
as ever, see details of compiler's doing, can utilize ildasm (or reflector in il mode, example) , see generated il.
c# lambda anonymous-methods
No comments:
Post a Comment