C#动态编译字符串和.cs文件
我正在开发一个网站,用户可以在该网站上针对浏览器文本区域中的问题实现 C# 代码解决方案并提交。然后,服务器将将该代码与我在服务器上提供的预定义接口一起编译。将其视为一种策略设计模式;我提供一个策略接口,由用户实现。所以我需要在运行时一起编译一个字符串和一个预定义的 *.cs 文件。这是我现在仅编译字符串部分的代码:
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);
用户将提交如下内容:
public class UserClass : IStrategy
{
public string ExecuteSolution(string input)
{
// user code
}
}
抛开安全问题(这是另一天的一个沉重问题)...我如何将其与我的预定义接口 *.cs 文件一起编译?或者有更好的方法来处理这个问题吗?
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
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
CodeDomProvider.CompileAssemblyFromSource()
被定义为这意味着您可以从多个源文件编译一个程序集。类似的:
另一个(可能更好)选择是引用包含您需要的代码的已编译程序集。您可以使用
CompilerParameters.ReferencedAssemblies 来执行此操作
:
CodeDomProvider.CompileAssemblyFromSource()
is defined asThat means you can compile one assembly from multiple source files. Something like:
Another (possibly better) option is to reference already compiled assembly that contains the code you need. You can do this using
CompilerParameters.ReferencedAssemblies
: