c# - Can Roslyn be used to generate dynamic method similar to DynamicMethod IL generation -


i have been using dynamimethod generate il using

method.getilgenerator(); 

this works of course hard use since don't want work low level il in high level language c#. since there roslyn though can use instead. have tried figure out how use roslyn similar thing: generate dynamic method , create delegate it. way able have full class this

syntaxtree syntaxtree = csharpsyntaxtree.parsetext(@" using system;  namespace roslyncompilesample {     public class writer     {         public void write(string message)         {             console.writeline(message);         }     } }"); 

then instead of write method can insert method inside using string concatenation. after dynamic assembly generated in memory , loaded , reflection used required method , generate delegate.

this method seems work fine seems bit of overkill case need use multiple independent methods possible leading lots of assemblies being loaded.

so question is: there easy way similar dynamic method roslyn, can define body of method attached type? if not, there big drawback in compiling many dynamic assemblies (like many can't loaded, etc...)

you can use csharpscript class. await csharpscript.evaluateasync("1 + 2") evaluates expression. can find in microsoft.codeanalysis.scripting.csharp package (currently prerelease version). add usings , assembly references using scriptoptions (second parameter).

compile expression delegate:

var func = csharpscript.create<int>("1 + 3").compiletodelegate() 

passing function using globals object:

await csharpscript.create<int>("1 + x",       scriptoptions.default.addreferences(typeof(program).assembly),      globalstype:  typeof(scriptglobals))     .createdelegate()     .invoke(new scriptglobals() { x = 4 }); 


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -