C#动态编译引擎-CS-Script 简单使用

Technorati 标记:

介绍可以参看  http://www.cnblogs.com/shanyou/p/3413585.html

还可以参看 这个  项目介绍 性能测试 csscript使用 

项目官网 http://www.csscript.net/FAQ.html#_alternatives

使用

using CSScriptLibrary;

int a = 1;
int b = 3;
string scriptCode = "using System;
                        " +
                        "public class Calc                      " +
                        "{                                      " +
                        "   static public int Sum(int a, int b) " +
                        "   {                                   " +
                        "      return a + b;                    " +
                        "   }                                   " +
                        "}";


AsmHelper helper = new AsmHelper(CSScript.LoadCode(scriptCode, null, false));
int result= (int)helper.Invoke("Calc.Sum", a, b);

scriptCode 就是要执行的代码

CSScript.LoadCode 加载代码

AsmHelper 反射的帮助类

下面的东东卸载和删除执行后生成的assembly 文件

    string asmFile = CSScript.CompileCode(scriptCode, null, false);
    using (AsmHelper helper = new AsmHelper(asmFile, "tempDomain", true))
    {
          return (int)helper.Invoke("Calc.Sum", a, b);
    }

下面的东东 调用类的实例   calc 脚本里的类

object calc = helper.CreateObject("Calc");
return (int)helper.InvokeInst(calc, "sum", a, b);

对调用的方法进行限制  如静态方法

static int PrintSum(int a, int b)
{
    var printSum = CSScript.LoadMethod(
        @"public static void PrintSum(int a, int b)
          {
              Console.WriteLine((a+b));
          }")
          .GetStaticMethod();

    printSum(1, 2);
}

当然也可以调用文件

CSScript.Load(“hello.cs”)
 

需要注意的是   命名空间的声明和调用方法的引用   不要和原来的方法或者类发生冲突

helper.Invoke("MyNamespace.MyClass.SayHello", "Hello World!");

动态调用 js

可以使用这个 IronJS

原文地址:https://www.cnblogs.com/wang2650/p/4780551.html