我正在运行时构建一段代码并编译它的运行时。现在我需要在运行时获取动态代码中变量的结果。这是我的代码:
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 的值,以及如何获取它。
答案 0 :(得分:1)
您需要添加一个新的类似代码以使用“Example.exe”作为参考,并使用“Program”类来获取结果。此外,您需要手动触发main并且应该具有静态变量来存储结果。还需要在读取该变量之前保持该程序的完成。
如果我理解它是正确的,那么您正在编译并运行尚未创建的可执行文件。 这意味着,您需要假设其成功创建并使用字符串中的代码,并创建一个可执行文件来运行它。
答案 1 :(得分:1)
(1 )您可以将编译的程序集作为代码段加载,并使用任何直接传递合同的参数调用任何方法。以下修改示例打印
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
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) {}
public static string Main1(int abc) {
bool myresult=false;
if(abc==10)
myresult=true;
else
myresult=false;
return abc.ToString() + "": "" + (myresult ? ""myresult is true"" : ""myresult is false"");
}
}");
results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
var scriptClass = results.CompiledAssembly.GetType("Program");
var scriptMethod1 = scriptClass.GetMethod("Main1", BindingFlags.Static | BindingFlags.Public);
Console.WriteLine(scriptMethod1.Invoke(null, new object[] { 10 }).ToString());
Console.WriteLine(scriptMethod1.Invoke(null, new object[] { 20 }).ToString());
}
}
(2)或者您可以使用您想要的任何命令行参数运行已编译的Example.exe
,解析它们并以您想要的任何方式返回结果。控制台应用程序通常通过文件传递复杂的输入或输出结果,整体成功/失败通过Process.ExitCode指示。有很多可用的选项,其中一些在Stack Overflow问题Returning a string from a console application