c# - 作为程序的一部分在运行时编译代码

标签 c#

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

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";它在文件或数据库中。

有一个form.A Textbox in form。 我想在运行时使用字符串代码作为我的程序的一部分。

最佳答案

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

关于c# - 作为程序的一部分在运行时编译代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15470102/

相关文章:

javascript - 如何使 OnClick 与 jQuery maphilight 一起工作

c# - 无法从 MSBuild 引用 Nuget 包的 "tools"文件夹中的可执行文件

c# - 在 C# 中的字符串中查找指定字符串的所有索引

c# - async 真的能让调用者等待吗?

c# - 如何在 iOS 上的 Google Play 游戏服务中禁用推送通知权限?

javascript - 如何在服务器端监听客户端事件

c# - .NET JWT token 验证的命名空间 : System vs. Microsoft

c# - VSCode OmniSharp/C# intellisense 看不到 Ionide/F# lib 模块/命名空间

c# - 如何长时间监控 IObservable<double> 是否超出范围

c# - C# 中的重载方法