Dynamic execution of the text file C# code fragment
Question:
Can the C# code fragment be stored in the text file and dynamically execute it? In order to obtain the best performance, should I compile the code first?
Answer:
Yes, you can dynamically compile and execute the C# code fragment. For static .NET language like C#, the best way is to use Codedom (code document object model). CODEDOM can dynamically build and execute code fragments.
CSHARPCODEPROVIDER provides an interface to compile the C# code. Examples as follows:
From text compilation code:
To compile the code from the text, please use Compileassemblyfromsource:
using System.CodeDom.Compiler; using Microsoft.CSharp; var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
<行> Execute the compiled code (use reflection):
After the compilation is completed, use reflection to dynamically load and execute the assembly:
var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true); parameters.GenerateExecutable = true; CompilerResults results = csc.CompileAssemblyFromSource(parameters, codeText);
The above is the detailed content of Can C# Code Fragments Be Dynamically Executed from a Text File, and Should They Be Compiled for Optimal Performance?. For more information, please follow other related articles on the PHP Chinese website!