是否有可能建立/ C#执行code在运行时间?有可能、时间、code

2023-09-02 21:12:22 作者:Pour toi 为你

我知道你可以动态创建一个使用散发出.NET程序集,的System.Reflection并作为这里显示手动创建的IL code。

不过,我想知道是否有可能以动态创建和执行C#code座的实时性,在运行的应用程序。感谢您的任何输入或想法。

编辑:的 据我所知codeDOM让你编译C#code成EXE文件,而不是仅仅执行它。这里的一些背景资料,以及为什么(据我可以告诉),这是不是对我来说是最好的选择。我创建了将要执行这样一个动态创建的code相当多的应用[备案 - 这是学术研究,而不是一个真实的应用程序,因此这是无法避免的。因此,创建/执行数千个动态创建EXE文件是不是真的有效。其次 - 所有动态code片段返回一些数据,是很难从单独运行的EXE阅读。请让我知道如果我失去了一些东西。

至于DynamicMethod的做法,指出的乔恩斯基特的,一切都会像一个魅力,如果有将是一个更简单的方法来写C本身的$ C $,而不是低水平的IL $ C $ ℃。

换句话说的(很严厉地说)我需要的是这样的:

 字符串x =_some C#code here_;
VAR的结果= Exec的(X);
 

解决方案

当然 - 这也正是我做Snippy例如,对于C#的深度。你可以在这里下载源$ C ​​$ C - 它使用CSharp$c$cProvider.

另外还有建筑前pression树,然后汇编成委托,使用的可能性DynamicMethod,或DLR在.NET 4 ...各种各样的东西。

I know you can dynamically create a .NET assembly using Emit, System.Reflection and manually created IL code as shown here.

VSCode配置C 运行环境

But I was wondering is it possible to dynamically create and execute C# code block real-time, in a running application. Thanks for any input or ideas.

Edit: As I understand CodeDOM allows you to compile C# code into EXE file rather than "just" executing it. Here's some background information and why (as far as I can tell) this isn't the best option for me. I'm creating an application that will have to execute such a dynamically created code quite a lot [for the record - it's for academic research, not a real-world application, thus this cannot be avoided]. Therefore, creating/executing thousands of dynamically created EXEs aren't really efficient. Secondly - all dynamic code fragments returns some data that is hard to read from separately running EXE. Please let me know if I'm missing something.

As for DynamicMethod approach, pointed out by Jon Skeet, everything would work like a charm if there would be an easier way to write the code itself rather than low level IL code.

In other words (very harshly speaking) I need something like this:

string x = "_some c# code here_";
var result = Exec(x);

解决方案

Absolutely - that's exactly what I do for Snippy for example, for C# in Depth. You can download the source code here - it uses CSharpCodeProvider.

There's also the possibility of building expression trees and then compiling them into delegates, using DynamicMethod, or the DLR in .NET 4... all kinds of things.