C#动态串和cs文件编译 [英] C# dynamic compilation of string and .cs file

查看:289
本文介绍了C#动态串和cs文件编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个网站,用户可以实现在浏览器文本区C#code解决问题的方法,并提交。然后,服务器将共同编译code以predefined接口我公司提供的服务器上。你可以把它作为一个战略设计模式;我提供了一个战略的界面和用户实现它。所以,我需要编译字符串,并pdefined *的.cs在运行时文件一起$ P $。这里的code我现在有只编译字符串部分:

I'm working on a website where a user can implement a C# code solution to a problem in a browser text area and submit it. The server will then compile that code together with a predefined interface I provide on the server. Think of it as a strategy design pattern; I provide a strategy interface and users implement it. So I need to compile a string and a predefined *.cs file together at run-time. Here's the code I have now that compiles only the string portion:

CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");

CompilerParameters parameters = new CompilerParameters();
parameters.OutputAssembly = "CodeOutputTest.dll";   // need to name this dynamically.  where to store it?
parameters.GenerateExecutable = false;
parameters.IncludeDebugInformation = false;

CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, request.Code);

用户将提出这样的:

Users would submit something like this:

public class UserClass : IStrategy
{
     public string ExecuteSolution(string input)
     {
         // user code
     }
}

安全问题放在一边(这是一个沉重的问题,另一天)......我怎么能编译这与我的predefined接口* .cs文件?还是有处理这更好的办法吗?

Security concerns aside (that's a heavy question for another day)...how can I compile this together with my predefined interface *.cs file? Or is there a better way of handling this?

谢谢!

推荐答案

<一个href="http://msdn.microsoft.com/en-us/library/system.$c$cdom.compiler.$c$cdomprovider.compileassemblyfromsource.aspx"相对=nofollow> codeDomProvider.CompileAssemblyFromSource() 被定义为

public virtual CompilerResults CompileAssemblyFromSource(
    CompilerParameters options, params string[] sources)

这意味着您可以从多个源文件编译一个程序集。是这样的:

That means you can compile one assembly from multiple source files. Something like:

codeProvider.CompileAssemblyFromSource(parameters, request.Code, otherCode);

另一个(可能更好)的选择是引用包含code,你需要已经编译的程序集。你可以用做<一个href="http://msdn.microsoft.com/en-us/library/system.$c$cdom.compiler.compilerparameters.referencedassemblies.aspx"相对=nofollow> CompilerParameters.ReferencedAssemblies

parameters.ReferencedAssemblies.Add("SomeLibrary.dll");

这篇关于C#动态串和cs文件编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆