Home >Backend Development >C++ >Can C# Code Fragments Be Dynamically Compiled and Executed from a File or Stream?
dynamic compilation and execution of the code fragment
Question:
Can it dynamically compile and execute the C#code fragment saved in the file or input stream?
Answer:
Of course! In C#and other static .NET language, CODEDOM (code document object model) is the best solution for such tasks. It can also be used as a dynamic constructing code segment or the entire class. Implement:
To achieve dynamic compilation, use CSHARPCODEPROVIDER class. Examples as follows:
Execution:
To execute the compiled code, use the reflex dynamic loading assembly.
<code class="language-csharp">using System; using System.Collections.Generic; using Microsoft.CSharp; using System.CodeDom.Compiler; public class Program { public static void Main(string[] args) { // 创建C#代码提供程序 var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } }); // 设置编译器参数 var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true); parameters.GenerateExecutable = true; // 编译代码 CompilerResults results = csc.CompileAssemblyFromSource(parameters, @" using System.Linq; public class Program { public static void Main(string[] args) { var q = from i in Enumerable.Range(1,100) where i % 2 == 0 select i; foreach(var item in q) { Console.WriteLine(item); } } }" ); // 处理任何错误 foreach (CompilerError error in results.Errors) { Console.WriteLine(error.ErrorText); } } }</code>Example:
By using Codedom, you can dynamically compile and execute the C#code fragment to provide strong and universal solutions for your programming needs. Please note that
will be created in your project output directory. This code will printed all the even numbers between 1 to 100.
The above is the detailed content of Can C# Code Fragments Be Dynamically Compiled and Executed from a File or Stream?. For more information, please follow other related articles on the PHP Chinese website!