【问题标题】:execute c# code at runtime from code file在运行时从代码文件执行 c# 代码
【发布时间】:2025-12-26 19:25:12
【问题描述】:

我有一个包含按钮的 WPF C# 应用程序。

按钮单击的代码写在单独的文本文件中,该文件将放置在应用程序运行时目录中。

我想在单击按钮时执行放置在文本文件中的代码。

知道怎么做吗?

【问题讨论】:

标签: c# .net runtime csharpcodeprovider


【解决方案1】:

执行编译的即时类方法的代码示例:

using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string source =
            @"
namespace Foo
{
    public class Bar
    {
        public void SayHello()
        {
            System.Console.WriteLine(""Hello World"");
        }
    }
}
            ";

             Dictionary<string, string> providerOptions = new Dictionary<string, string>
                {
                    {"CompilerVersion", "v3.5"}
                };
            CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

            CompilerParameters compilerParams = new CompilerParameters
                {GenerateInMemory = true,
                 GenerateExecutable = false};

            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);

            if (results.Errors.Count != 0)
                throw new Exception("Mission failed!");

            object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
            MethodInfo mi = o.GetType().GetMethod("SayHello");
            mi.Invoke(o, null);
        }
    }
}

【讨论】:

  • 我在内存编译中添加了
  • 请发布您的代码示例。我的代码没有出现文件未找到异常。
  • 我在新的控制台中执行相同的代码,没有任何改变。
  • 这对我来说很好用。可以给我抛出异常的调用堆栈吗?
  • @VinodMaurya 我注意到如果编译失败,我会得到 File not found。在尝试调用之前检查 results.Errors.Count。
【解决方案2】:

您可以使用Microsoft.CSharp.CSharpCodeProvider 即时编译代码。具体见CompileAssemblyFromFile

【讨论】:

    【解决方案3】:

    我建议查看Microsoft Roslyn,特别是它的ScriptEngine 类。 以下是一些很好的例子:

    1. Introduction to the Roslyn Scripting API
    2. Using Roslyn ScriptEngine for a ValueConverter to process user input

    使用示例:

    var session = Session.Create();
    var engine = new ScriptEngine();
    engine.Execute("using System;", session);
    engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
    engine.Execute("MessageBox.Show(Sin(1.0));", session);
    

    【讨论】:

    • 在搜索下载之前,只需使用 Package-Manager:Install-Package Roslyn
    【解决方案4】:

    看起来有人为此创建了一个名为 C# Eval 的库。

    编辑:更新了指向 Archive.org 的链接,因为 original site 似乎已死。

    【讨论】:

    • @RichO'Kelly,谢谢 - 我已将其更新为指向 archive.org 版本。
    【解决方案5】:

    您需要的是CSharpCodeProvider Class

    有几个示例可以了解它是如何工作的。

    1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi

    这个例子的重点是你实际上可以做所有事情。

    myCompilerParameters.GenerateExecutable = false;
    myCompilerParameters.GenerateInMemory = false;
    

    2http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime

    这个例子很好,因为你可以创建 dll 文件,所以它可以在其他应用程序之间共享。

    基本上你可以搜索http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6并获得更多有用的链接。

    【讨论】: