【发布时间】:2014-10-27 05:33:29
【问题描述】:
我在运行时构建一段代码并在运行时编译它。现在我需要在运行时获取动态代码中变量的结果。这是我的代码:
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" }, "Example.exe", true);
parameters.GenerateExecutable = true;
CompilerResults results = csc.CompileAssemblyFromSource(parameters,
@"using System.Linq;
class Program {
public static void Main(string[] args) {
int abc=10;
bool myresult=false;
if(abc==10)
myresult=true;
else
myresult=false;
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
}
}
我希望运行时代码在我的主程序中返回 myresult 变量的值以及如何获取它。
【问题讨论】:
-
编译代码后,您可以简单地使用
Process类执行结果文件并从中捕获ExitCode。顺便说一句:然后您可以优化您的代码:Environment.Exit(abc == 10); -
我按照链接中给出的示例进行了尝试。但它仍然没有工作blackwasp.co.uk/RuntimeCompilation_2.aspx
-
@sia 遵循
ShowExpressionResults中的示例(在您的链接中),它加载已编译的程序集,在其中找到一个类,在类中找到一个方法并运行该方法并打印该方法的输出 -
将再次尝试并更新结果..
标签: c# variables compiler-construction