How can I evaluate C# code dynamically?

后端 未结 16 1962
[愿得一人]
[愿得一人] 2020-11-22 03:37

I can do an eval(\"something()\"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?

An example of what I

16条回答
  •  后悔当初
    2020-11-22 04:08

    I have written a package, SharpByte.Dynamic, to simplify the task of compiling and executing code dynamically. The code can be invoked on any context object using extension methods as detailed further here.

    For example,

    someObject.Evaluate("6 / {{{0}}}", 3))
    

    returns 3;

    someObject.Evaluate("this.ToString()"))
    

    returns the context object's string representation;

    someObject.Execute(@
    "Console.WriteLine(""Hello, world!"");
    Console.WriteLine(""This demonstrates running a simple script"");
    ");
    

    runs those statements as a script, etc.

    Executables can be gotten easily using a factory method, as seen in the example here--all you need is the source code and list of any expected named parameters (tokens are embedded using triple-bracket notation, such as {{{0}}}, to avoid collisions with string.Format() as well as Handlebars-like syntaxes):

    IExecutable executable = ExecutableFactory.Default.GetExecutable(executableType, sourceCode, parameterNames, addedNamespaces);
    

    Each executable object (script or expression) is thread-safe, can be stored and reused, supports logging from within a script, stores timing information and last exception if encountered, etc. There is also a Copy() method compiled on each to allow creating cheap copies, i.e. using an executable object compiled from a script or expression as a template for creating others.

    Overhead of executing an already-compiled script or statement is relatively low, at well under a microsecond on modest hardware, and already-compiled scripts and expressions are cached for reuse.

提交回复
热议问题