Compiling C# code from txt file to interface with running wpf application

三世轮回 提交于 2019-12-24 09:39:52

问题


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.



来源:https://stackoverflow.com/questions/5557144/compiling-c-sharp-code-from-txt-file-to-interface-with-running-wpf-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!