繁体   English   中英

作为程序一部分在运行时进行代码编译

[英]Code Compiling on Runtime as part of program

编写此代码段是在运行时编译代码。 编译后的代码与任何其他程序一样工作。 可以使用反射。 我想做一些不同的事情。

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

例如 :

我的代码是Textbox1.Text =“ 123”; 它在文件或数据库中。

有一个表单。表单中有一个文本框。 我想在运行时将字符串代码用作程序的一部分。

为此,您可以将函数名称更改为string_Function而不是Main。 将上述代码段另存为.cs文件。 说出Code_Snippet.cs。 现在将此文件添加到您的MainProject中。 无论您想在何处使用此代码段,都必须编写代码行,例如Code_Snippet.String_Function(TextBox.Text);。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM