2013-06-23 49 views
0

我想在我的应用程序中编译一个C#控制台应用程序,并以某种方式获取返回的结果。我想这默默的发生(我不希望控制台实际显示等),可以说,我有这样的代码构建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

我可能会在一个单独的线程创建它,如果你希望它发生默默 – Stokedout

+0

单独的线程部分是不难的,我知道的事实,这会是多线程的。我只需要一般的执行方法并获取值 –

+1

它看起来像你从代码[Code0987 linked article]复制你的代码(http://www.codeproject.com/Articles/9019/Compiling-and-Executing-Code-at -运行)。为什么只使用文章的一部分,并询问在文章其余部分中解释的内容? – svick

回答

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功能。

Source

+0

你从哪里找到它的? – svick

+0

并返回值? –

+0

是的,它会返回您调用的函数返回的值。 – Code0987

相关问题