You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否从文本生成/运行代码?求相关技术名称及实现方法

动态代码编译与执行技术(C#场景)

你要找的是动态代码编译与执行技术,在C#生态里有两种主流实现方案:

  • Roslyn(.NET Compiler Platform):微软官方推出的现代编译平台,支持动态解析、编译并执行C#代码文本,是当前的首选方案。
  • CodeDOM:较早期的动态编译API,适用于旧版.NET框架,现在更多被Roslyn替代。

以下是用Roslyn实现你需求的可运行示例:

using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.Reflection;

public static void RunMyFunction()
{
    // 定义要执行的代码文本
    string codeText = @"
        using System;
        public class DynamicCodeBlock
        {
            public static void Run()
            {
                Console.WriteLine(""Hello world"");
            }
        }
    ";

    // 解析代码语法树
    var syntaxTree = CSharpSyntaxTree.ParseText(codeText);
    
    // 添加必要的程序集引用
    var assemblyReferences = new[]
    {
        MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
        MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)
    };

    // 创建编译对象
    var compilation = CSharpCompilation.Create(
        "DynamicExecAssembly",
        syntaxTrees: new[] { syntaxTree },
        references: assemblyReferences,
        options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

    // 将编译结果输出到内存流
    using var memoryStream = new System.IO.MemoryStream();
    EmitResult emitResult = compilation.Emit(memoryStream);

    // 检查编译是否成功
    if (!emitResult.Success)
    {
        foreach (var error in emitResult.Diagnostics)
        {
            Console.WriteLine($"编译错误: {error}");
        }
        return;
    }

    // 加载编译后的程序集并执行目标方法
    memoryStream.Seek(0, System.IO.SeekOrigin.Begin);
    Assembly dynamicAssembly = Assembly.Load(memoryStream.ToArray());
    Type dynamicType = dynamicAssembly.GetType("DynamicCodeBlock");
    MethodInfo targetMethod = dynamicType.GetMethod("Run");
    targetMethod.Invoke(null, null);
}

关键注意事项

  • 动态执行外部来源的代码存在极高安全风险,可能被用于注入恶意代码,生产环境使用时必须对输入代码做严格的校验与沙箱隔离。
  • 若仅需执行简单表达式(而非完整类/方法),Roslyn也支持单独的表达式求值能力,无需定义完整类结构。

内容的提问来源于stack exchange,提问作者CSharpMan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:10:11