Use IronJs to run javascript scripts in .NET programs

Use IronJs to run javascript scripts in .NET programs

what's dlr

The dynamic language runtime (DLR) is a runtime environment that adds a set of services for dynamic languages ​​to the common language runtime (CLR). The DLR makes it easier to develop dynamic languages ​​to run on the .NET Framework and to add dynamic features to statically typed languages.

Dynamic languages ​​can identify the type of an object at run time, whereas in statically typed languages ​​such as C# and Visual Basic (when you use Option Explicit On) you must specify object types at design time. Examples of dynamic languages ​​are Lisp, Smalltalk, JavaScript, PHP, Ruby, Python, ColdFusion, Lua, Cobra, and Groovy.

With such a pile of foreign texts laid out, it was lazy to translate. To put it more straightforwardly, DLR gives .NET the ability to execute a scripting language (maybe the description is not accurate, but you can understand it this way).

why use IronJs

Based on DLR, Microsoft has opened two sets of libraries to run python and ruby. But I think that javascript is more versatile. If you are a programmer, you must have written javascript by 90%.

what problem can be solved

So what are the benefits of this ability. What I can think of is that for some of the logic in the system that needs to be changed frequently, such as discount algorithms, points, and various rules, we can mention it in the script to write. In this way, without any compilation, ctrl+s can solve the problem.

this is demo:

code:

            var jsContext = new IronJS.Hosting.CSharp.Context();
            jsContext.ExecuteFile("myDlr.js");
            var fun = jsContext.GetFunctionAs<Func<double, double, double>>("cacl");
            double a = Double.Parse(this.tbxA.Text);
            double b = Double.Parse(this.tbxB.Text);
            var result = fun.Invoke(a,b);
            this.tbxResult.Text = result.ToString();

js:

            var cacl = function (a, b) {
            return a*b;
           };

When I change a*b to ab, the result directly becomes -10. No need to close the program, no need to compile the program, cool.

Reference: https://cloud.tencent.com/developer/article/1013360 Use IronJs to run javascript scripts in .NET programs-Cloud + Community-Tencent Cloud