c# - 在 Mono.Csharp 中运行小程序

标签 c# compiler-construction mono bootstrapping

我正在尝试编写一个交互式 C# 教学应用程序,用户可以在其中试验/更改代码示例并查看会发生什么(有点像 jsfiddle)。

我找到了很多小表达式或类似 REPL 的使用 Mono.Csharp 作为运行时编译器的示例,但我找不到执行“迷你程序”的示例。

到目前为止,这是我的玩具代码(一个 MVC Action )。 “代码”参数直接从文本区域发布。

[HttpPost]
public ActionResult Index(string code)
{
    var reportWriter = new StringWriter();
    var settings = new CompilerSettings();
    var printer = new ConsoleReportPrinter(reportWriter);
    var reports = new Report(printer);
    var eval = new Evaluator(settings, reports);

    var model = new CodeViewModel();
    model.Code = code;
    eval.Run(code);
    model.Result = reportWriter.ToString();

    return View("Index", model);
}

现在假设代码是这样的字符串:

using System;
public class MyClass
{
    public void DoSomething()
    {
        Console.WriteLine("hello from DoSomething!");
    }
}

我如何引导它(即实例化一个 MyClass 对象并对其调用 DoSomething)?我试过将 new MyClass().DoSomething(); 附加到最后,但我明白了:

{interactive}(1,2): warning CS0105: The using directive for `System' appeared previously in this namespace
{interactive}(1,8): (Location of the symbol related to previous warning)
{interactive}(11,1): error CS1530: Keyword `new' is not allowed on namespace elements
{interactive}(11,4): error CS1525: Unexpected symbol `MyClass', expecting `class', `delegate', `enum', `interface', `partial', or `struct'

我错过了什么?

最佳答案

var reportWriter = new StringWriter();
var settings = new CompilerSettings();
var printer = new ConsoleReportPrinter(reportWriter);
var reports = new Report(printer);
var eval = new Evaluator(settings, reports);

eval.Run(code);

eval.Run(@"
    var output = new System.IO.StringWriter(); 
    Console.SetOut(output);
    new MyClass().DoSomething();");

var model = new CodeViewModel();
model.Code = code;

if (reports.Errors > 0)
   model.Result = reportWriter.ToString();
else
   model.Result = (string) eval.Evaluate("output.ToString();");

return View("Index", model);

关于c# - 在 Mono.Csharp 中运行小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12633378/

相关文章:

c# - 如何访问传递给构造函数的 ref bool 变量?

c# - 在 C# 中为我的应用程序编写 API

c++ - 在线C++编译器: output binary files for me?

c# - 使用 Mono C# 编译器作为服务(错误)

mono - 在 Ubuntu 中从 tarball 编译 MonoDevelop 4.2.2 时出错

c# - MonoTouch NSClassFromString

c++ - 在线裁判系统

java - 将 Maven Java 编译器调试设置为 false 不会删除行号表?

java - 使用 SpringFlux 的 webclient 重复 Mono

c# - 查看包含*很多*列的表格的最佳方式?