How can I evaluate C# code dynamically?

后端 未结 16 1938
[愿得一人]
[愿得一人] 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 an open source project, Dynamic Expresso, that can convert text expression written using a C# syntax into delegates (or expression tree). Expressions are parsed and transformed into Expression Trees without using compilation or reflection.

    You can write something like:

    var interpreter = new Interpreter();
    var result = interpreter.Eval("8 / 2 + 2");
    

    or

    var interpreter = new Interpreter()
                          .SetVariable("service", new ServiceExample());
    
    string expression = "x > 4 ? service.SomeMethod() : service.AnotherMethod()";
    
    Lambda parsedExpression = interpreter.Parse(expression, 
                              new Parameter("x", typeof(int)));
    
    parsedExpression.Invoke(5);
    

    My work is based on Scott Gu article http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx .

    0 讨论(0)
  • 2020-11-22 04:08

    You also could implement a Webbrowser, then load a html-file wich contains javascript.

    Then u go for the document.InvokeScript Method on this browser. The return Value of the eval function can be catched and converted into everything you need.

    I did this in several Projects and it works perfectly.

    Hope it helps

    0 讨论(0)
  • 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<int>("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.

    0 讨论(0)
  • 2020-11-22 04:10

    I don't now if you absolutely want to execute C# statements, but you can already execute Javascript statements in C# 2.0. The open-source library Jint is able to do it. It's a Javascript interpreter for .NET. Pass a Javascript program and it will run inside your application. You can even pass C# object as arguments and do automation on it.

    Also if you just want to evaluate expression on your properties, give a try to NCalc.

    0 讨论(0)
  • 2020-11-22 04:11

    Unfortunately, C# isn't a dynamic language like that.

    What you can do, however, is to create a C# source code file, full with class and everything, and run it through the CodeDom provider for C# and compile it into an assembly, and then execute it.

    This forum post on MSDN contains an answer with some example code down the page somewhat:
    create a anonymous method from a string?

    I would hardly say this is a very good solution, but it is possible anyway.

    What kind of code are you going to expect in that string? If it is a minor subset of valid code, for instance just math expressions, it might be that other alternatives exists.


    Edit: Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here.

    If you split the string by the ; first, to get individual properties, you can use the following code to get a PropertyInfo object for a particular property for a class, and then use that object to manipulate a particular object.

    String propName = "Text";
    PropertyInfo pi = someObject.GetType().GetProperty(propName);
    pi.SetValue(someObject, "New Value", new Object[0]);
    

    Link: PropertyInfo.SetValue Method

    0 讨论(0)
  • 2020-11-22 04:11

    Not really. You can use reflection to achieve what you want, but it won't be nearly as simple as in Javascript. For example, if you wanted to set the private field of an object to something, you could use this function:

    protected static void SetField(object o, string fieldName, object value)
    {
       FieldInfo field = o.GetType().GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
       field.SetValue(o, value);
    }
    
    0 讨论(0)
提交回复
热议问题