C#动态编译器,在内存中编译时获取标准输出

标签 c# dynamic-compilation

我想获取动态编译代码的标准输出。

我的代码:

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

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            var source = File.ReadAllText("form.cs");

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

            CompilerParameters compilerParams = new CompilerParameters
            {
                GenerateInMemory = true,
                GenerateExecutable = false,
                ReferencedAssemblies =  {"System.dll" ,"mscorlib.dll"}
        };
            CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
            Assembly assembly = results.CompiledAssembly;
            Type program = assembly.GetType("program.TestPerson");
            MethodInfo main = program.GetMethod("Main");
            var outp= main.Invoke(null, null);
            //Console.WriteLine(outp);
            Console.ReadLine();
        }
    }
}

form.cs的内容:

using System;
namespace program {
    public class TestPerson
    {
         public static void Main()
        {
            var person1 = new Person();
            Console.WriteLine(person1.Name);
        }
    }
}

public class Person
{
    public Person()
    {
        Name = "unknown";
    }
        public Person(string name)
        {
            Name = name;
        }
        public string Name { get;set; }
        public override string ToString()
        {
            return Name;
        }
    }

我真正想要的是在父应用程序的变量中编译后拥有 form.cs (Console.WriteLine) 的标准输出,顺便说一句,我不想​​将代码构建到文件中并将其作为进程运行并阅读它的输出。 还假设 form.cs 的内容不可编辑。

最佳答案

main 可能让您感到困惑,但正如我在评论中所写,您的动态编译代码不会在其自己的进程中运行(这也可以实现,但要复杂得多), 因此它没有自己的输出。 main 方法只是当前进程中默认 AppDomain 中另一个类中的另一个方法。这意味着它将写入您的外部托管 进程的控制台。您必须使用 Console.SetOut 捕获该输出。请参阅以下 linqpad 代码段:

string source = @"using System;
namespace program {
    public class TestPerson
    {
        public static void Main()
        {
            Console.WriteLine(""TEST"");
        }
    }
}";

void Main()
{
    Dictionary<string, string> providerOptions = new Dictionary<string, string>
            {
                {"CompilerVersion", "v4.0"}
            };
    CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);

    CompilerParameters compilerParams = new CompilerParameters
    {
        GenerateInMemory = true,
        GenerateExecutable = false,
        ReferencedAssemblies = { "System.dll", "mscorlib.dll" }
    };
    CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
    Assembly assembly = results.CompiledAssembly;
    Type program = assembly.GetType("program.TestPerson");
    MethodInfo main = program.GetMethod("Main");

    var sb = new StringBuilder();
    var writer = new StringWriter(sb);
    Console.SetOut(writer);

    var outp = main.Invoke(null, null);

    sb.ToString().Dump(); // this Dump is from linqpad, do what you want with the StringBuilder content 

    Console.ReadLine();
 }

如果你想写到原始标准输出,先保存它,像这样:

...
var oldOut = Console.Out;
Console.SetOut(writer);

var outp = main.Invoke(null, null);

oldOut.WriteLine($"The result is: {sb.ToString()}");

关于C#动态编译器,在内存中编译时获取标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54007097/

相关文章:

c# - 如何检查字符串是否包含c#中的电子邮件

C# 无法识别的转义序列

C# - 切换泛型

c# - 在 Web Api 2 中启用 CORS

c# - winform 的动态代码编译在 C# 中给出错误

使用 AoT 的 Angular 5 动态模板

visual-studio-2015 - 动态编译在 ASP.NET 5 RC1 中仍然不起作用?

c# - 如何在 ElasticSearch 中设置索引的 TTL

asp.net - 运行 IIS Express 时 ASP.NET 网站的程序集在哪里

compilation - Java - 没有 JDK 的动态编译