Compiling C# code from txt file to interface with

2019-07-28 05:15发布

问题:

I have been searching online for a neat way to compile code at runtime and manipulate the running application's objects (properties etc.). I have come across Snippy, CodeDom and CSharpCodeProvider but I didn't completely understood how I can use those solutions in my application to do what I want. Bottom line is, I want to have a small portion of the code in an external file so I can swap out different code during run time (e.g. Formulas to manipulate Data and etc.) Could somebody explain to me how exactly can I implement this in a WPF application in a neat fashion? I just need to pass the external code some data and after execution it will return me some data that I can populate an object with. P.S: I also thought about parsing Mathematical expression from String and manipulate my data that way but if I can parse and execute C# code externally at run time, it will give me much more freedom and control over the formula and data. Thanks in advance.

回答1:

I think you would do better using .NET compatible dynamic language like IronPython or IronRuby. Those integrate pretty much seamlessly with C#/.NET and are actually designed to provide execution-time scriptability.

Trivial example of IronPython usage from Jon Skeet's C# in Depth:

// the python code
string python = @" 
text = 'hello' 
output = input + 1 
";

// setup the scripting engine
ScriptEngine engine = Python.CreateEngine(); 
ScriptScope scope = engine.CreateScope(); 
scope.SetVariable("input", 10); 
engine.Execute(python, scope); 

// the results
Console.WriteLine(scope.GetVariable("text")); 
Console.WriteLine(scope.GetVariable("input")); 
Console.WriteLine(scope.GetVariable("output"));

Needless to say, the scripts can use .NET Base Class Library and any extra methods you expose to them.