简体   繁体   中英

C# dynamic code evaluation, Eval, REPL

Does anyone know if there is a way to evaluate c# code at runtime. eg. I would like to allow a user to enter DateTime.Now.AddDays(1), or something similar, as a string and then evaluate the string to get the result.

I woder if it is possible to access the emmediate windows functionality, since it seems that is evaluates every line entered dynamically.

I have found that VB has an undocumented EbExecuteLine() API function from the VBA*.dll and wonder if there is something equivalent for c#.

I have also found a custom tool https://github.com/DavidWynne/CSharpEval (it used to be at kamimucode.com but the author has moved it to GitHub) that seems to do it, but I would prefer something that comes as part of .NET

Thanks

Mono has the interactive command line (csharp.exe)

You can look at it's source code to see exactly how it does it's magic:

https://github.com/mono/mono/raw/master/mcs/tools/csharp/repl.cs

As you've probably already seen, there is no built-in method for evaluating C# code at runtime. This is the primary reason that the custom tool you mentioned exists.

I also have a C# eval program that allows for evaluating C# code. It provides for evaluating C# code at runtime and supports many C# statements. In fact, this code is usable within any .NET project, however, it is limited to using C# syntax. Have a look at my website, http://csharp-eval.com , for additional details.

The O2 Platform's C# REPL Script Environment use the Fluent# APIs which have a real powerful reflection API that allows you do execute code snippets.

For example:

"return DateTime.Now.ToLongTimeString();".executeCodeSnippet(); 

will return

5:01:22 AM

note that the "...".executeCodeSnippet(); can actually execute any valid C# code snippet (so it is quite powerful).

If you want to control what your users can execute, I could use AST trees to limite the C# features that they have access to.

Also take a look at the Microsoft's Roslyn , which is VERY powerful as you can see on Multiple Roslyn based tools (all running Stand-Alone outside VisualStudio)

Microsoft's C# compiler don't have Compiler-as-a-Service yet (Should come with C# 5.0).

You can either use Mono's REPL , or write your own service using CodeDOM

Its not fast but you can compile the code on the fly, see my previous question ,

Once you have the assembly and you know the type name you can construct an instance of your compiled class using reflection and execute your method..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM