gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:21:12 25 4
gpt4 key购买 nike

我正在尝试编写一个交互式 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com