In a .net application, it is possible to save C # code in a text file or in a database as a string and execute dynamically on the fly. This method is useful in many cases, such as a business rule engine or a custom calculation engine, etc. here is a good example:
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
class Program
{
static void Main(string[] args)
{
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;
class Program {
public static void Main(string[] args) {
var q = from i in Enumerable.Range(1,100)
where i % 2 == 0
select i;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
The class of primary importance here is CSharpCodeProvider, which the compiler uses to compile code on the fly.
As you know, Python is a widely used high-level programming language. His design philosophy emphasizes code readability, but C # is more complicated than python. Therefore, it is better to use python for snippets of dynamic code instead of C #.
How to execute python dynamically in a c # application?
class Program
{
static void Main(string[] args)
{
var pythonCode = @"
a=1
b=2
c=a+b
return c";
}
}