从txt文件编译C#代码以与正在运行的wpf应用程序交互 [英] Compiling C# code from txt file to interface with running wpf application

查看:112
本文介绍了从txt文件编译C#代码以与正在运行的wpf应用程序交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在网上寻找一种巧妙的方法来在运行时编译代码并操纵正在运行的应用程序的对象(属性等).我遇到过Snippy,CodeDom和CSharpCodeProvider,但是我不完全理解如何在应用程序中使用这些解决方案来完成我想要的事情. 最重要的是,我想在外部文件中保留一小部分代码,以便我可以在运行时交换不同的代码(例如,用于处理数据的公式等).有人可以向我解释一下我该如何准确地实现这一点.简洁的WPF应用程序?我只需要向外部代码传递一些数据,执行后它将返回一些数据,我可以使用这些数据来填充对象. P.S:我还考虑过从String解析数学表达式并以这种方式操作数据,但是如果我可以在运行时从外部解析和执行C#代码,它将为我提供更多的自由和对公式和数据的控制.预先感谢.

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.

推荐答案

我认为您可以使用.a兼容的动态语言,例如 IronPython IronRuby .它们与C#/.NET几乎无缝集成,并且实际上旨在提供执行时脚本功能.

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.

Jon Skeet的深度学习C#的IronPython使用示例:

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"));

不用说,这些脚本可以使用.NET Base Class Library和您公开给它们的任何其他方法.

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

这篇关于从txt文件编译C#代码以与正在运行的wpf应用程序交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆