c# - 如何从字符串运行代码?

标签 c# dynamic-code

我的程序中有一个文本框。在文本框中,您可以编写要运行的函数/方法的名称以及传递参数。如果我的案例已填充,这将全部解析并通过一个大的开关 block 我为该特定案例的代码,以及传递参数。

但我真正想做的是使用stringbuilder构建源码然后运行!

这是使用我的 stringbuilder 构建的源代码示例。

 outlook outlooken = new outlook(appNwindow);

  outlooken.createNewEmail(scriptarray[i][1],scriptarray[i][2],
  scriptarray[i][3],scriptarray[i][4]);

使用stringbuilder创建字符串完全没有问题。但是我该如何运行它们呢?

我已经进行了很多测试,并设法让一切就绪,但我认为我遗漏了一些东西,因为我的代码总是会产生错误...

这是我的源代码

 CodeDomProvider myCodeDomeProvider = CodeDomProvider.CreateProvider("CSharp");
 String [] referenceAssemblies = {"System.dll"};
 //  string myAssemblyName = "myAssembly.dll";
 CompilerParameters myCompilerparameters = 
 new CompilerParameters(referenceAssemblies);

        myCompilerparameters.GenerateExecutable = false;
        myCompilerparameters.GenerateInMemory = true;

  //*** Here's the sourcecode it want to compile
  string[] arr1 = new string[] { "outlook outlooken = new outlook(appNwindow);","outlooken.createNewEmail(scriptarray[i][1],scriptarray[i][2],scriptarray[i[3],scriptarray[i][4]);"};

        CompilerResults myResults = myCodeDomeProvider.CompileAssemblyFromSource(myCompilerparameters, arr1);
        string objectname = "testet";
        string method = "createNewEmail";
        object[] args = new object[2];

        args[0] = "to";
        args[1] = "CC";

        if (myResults.Errors.HasErrors)

         {
            StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
            foreach (CompilerError error in myResults.Errors)
            {
            errors.AppendFormat("Line {0},{1}\t: {2}\n",
            error.Line, error.Column, error.ErrorText);
            }

            throw new Exception(errors.ToString());
            }
            else
            {
            Assembly assem = myResults.CompiledAssembly;
            object instance = null;

            Type type = assem.GetType(objectname);
            MethodInfo miChk = type.GetMethod(method);

            if (!miChk.IsStatic)
            {
            instance = assem.CreateInstance(objectname);
            type = instance.GetType();
            }

            MethodInfo mi = type.GetMethod(method);

            mi.Invoke(instance, args);
            }

这些是我在运行时遇到的错误:

附加信息:编译器错误:

第 1,1 行:命名空间不能直接包含字段或方法等成员

第 1,25 行:预期的类、委托(delegate)、枚举、接口(interface)或结构

第 1,1 行:命名空间不能直接包含字段或方法等成员

第 1,41 行:需要标识符

第 1,59 行:需要标识符

第 1,77 行:需要标识符

第 1,95 行:需要标识符

最佳答案

CodeDom 不会编译和执行任意语句。您编译的代码必须是有效的 C# 代码,就像您从源代码执行 C# 文件一样。

这意味着您需要将语句包装到命名空间 + 类中,并将其放在类中的方法(可以是静态的)中。

基本上,将输入想象成您正在编写一个普通的 C# 文件并使用编译器编译 .cs 文件 - 您需要在输入中使用相同的“文本”。

关于c# - 如何从字符串运行代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11804927/

相关文章:

c# - Excel 打开 XML 错误 : "found unreadable content" when creating simple example

c# - 进程无法访问文件,因为它被 mscorlib.dll 使用

c# - ASP.NET Core 2.1 应用程序未获得正确的 appsettings.json

visual-studio - 如何在Visual Studio中突出显示动态代码

C# 动态类型初始化器

java - 动态编译和执行代码的直接标准输出

javascript - 从 ES6 javascript 中的字符串动态创建方法(非浏览器)

c# - 这就是 WCF SSL 安全通道出错的原因吗?

c# - 如何将两个不同的列表映射到一个列表?