c# - converting a .net Func to a .net Expression<Func> -



c# - converting a .net Func<T> to a .net Expression<Func<T>> -

going lambda look easy using method call...

public void gimmeexpression(expression<func<t>> expression) { ((memberexpression)expression.body).member.name; // "dostuff" } public void somewhereelse() { gimmeexpression(() => thing.dostuff()); }

but turn func in expression, in rare cases...

public void containthedanger(func<t> dangerouscall) { seek { dangerouscall(); } grab (exception e) { // next line not work... expression<func<t>> dangerousexpression = dangerouscall; var nameofdanger = ((memberexpression)dangerouscall.body).member.name; throw new dangercontainer( "danger manifested while " + nameofdanger, e); } } public void somewhereelse() { containthedanger(() => thing.crossthestreams()); }

the line not work gives me compile-time error cannot implicitly convert type 'system.func<t>' 'system.linq.expressions.expression<system.func<t>>'. explicit cast not resolve situation. there facility overlooking?

ooh, it's not easy @ all. func<t> represents generic delegate , not expression. if there's way (due optimizations , other things done compiler, info might thrown away, might impossible original look back), it'd disassembling il on fly , inferring look (which no means easy). treating lambda expressions info (expression<func<t>>) magic done compiler (basically compiler builds look tree in code instead of compiling il).

related fact

this why languages force lambdas extreme (like lisp) easier implement interpreters. in languages, code , info same thing (even @ run time), our chip cannot understand form of code, have emulate such machine building interpreter on top of understands (the selection made lisp languages) or sacrificing powerfulness (code no longer equal data) extent (the selection made c#). in c#, compiler gives illusion of treating code info allowing lambdas interpreted code (func<t>) , data (expression<func<t>>) @ compile time.

c# .net lambda expression func

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -