compiler construction - Is it possible to dynamically compile and execute C# code fragments? -
I was wondering if it is possible to save the C # code piece in a text file (or an input stream), and Then execute those dynamically? Suppose that what I have been provided is compiled properly within a main () block, is it possible to compile and / or execute this code? I like to compile it for performance reasons.
At the very least, I can define an interface that they will need to implement, then they will provide the 'section' code that implements that interface. / P>
C # / all static. The best solution in NET languages is to use for such things (as a note, its other main purpose is to dynamically generate bits of code, or even whole classes.)
< P> Here's a nice little example, which also uses LINQ for fun. using the system; Using System.Collections.Generic; Using System.Linq; Use of Microsoft CSARP; Using System.CodeDom.Compiler; Class Program {Static Wide Men (String [] AGR) {var CSC = New CSHRP code provider (new dictionary & lt; string, string & gt; () {{"compiler warsen", "v5"}}); Var parameter = new compiler parameter (new [] {"mscorlib.dll", "System.Core.dll"}, "foo.exe", is true); Parameters Generate skillful = true; Compiler results result = csc.CompileAssemblyFromSource (criteria, @ "System.Linq; class program {public static zero main (using string [] ARG) {var q = I in enumerable.Range (1,100) where i% 2 = = 0 I choose;}} "); Results.Errors.Cast & lt; CompilerError & gt; (). ToList () ForEach (error => Console.WriteLine (error.ErrorText)); }} Here is the class of primary importance CSharpCodeProvider which uses the compiler to compile the code on the fly. If you want to run the code again, then you just have to use some reflection to load the assembly dynamically and execute it.
There is another example in C # (a little less concise) except for this it shows you exactly how to run runtime-compiled code using the System.Reflection namespace .
Comments
Post a Comment