我想在我的应用程序中编译一个C#控制台应用程序,并以某种方式获取返回的结果。我希望这是静默发生的(我不希望控制台实际显示等)让我说我有这个代码
private Assembly BuildAssembly(string code)
{
Microsoft.CSharp.CSharpCodeProvider provider =
new CSharpCodeProvider();
ICodeCompiler compiler = provider.CreateCompiler();
CompilerParameters compilerparams = new CompilerParameters();
compilerparams.GenerateExecutable = false;
compilerparams.GenerateInMemory = true;
CompilerResults results =
compiler.CompileAssemblyFromSource(compilerparams, code);
if (results.Errors.HasErrors)
{
StringBuilder errors = new StringBuilder("Compiler Errors :\r\n");
foreach (CompilerError error in results.Errors )
{
errors.AppendFormat("Line {0},{1}\t: {2}\n",
error.Line, error.Column, error.ErrorText);
}
throw new Exception(errors.ToString());
}
else
{
return results.CompiledAssembly;
}
}
我如何执行程序集并获得结果?
答案 0 :(得分:3)
这是我找到的东西 -
public object ExecuteCode(string code, string namespacename, string classname, string functionname, bool isstatic, params object[] args)
{
var asm = BuildAssembly(code);
object instance = null;
Type type;
if(isstatic)
{
type = asm.GetType(namespacename + "." + classname);
}
else
{
instance = asm.CreateInstance(namespacename + "." + classname);
type = instance.GetType();
}
return type.GetMethod(functionname).Invoke(instance, args);
}
此方法只是扩展了BuildAssembly函数。