我开发了一种测试脚本是否存在错误的方法:
public static object Test(string code, string references)
{
try
{
Compilation compilation = CSharpScript.Create(code,
options: ScriptOptions.Default
.AddReferences(references)
.AddImports("System.Collections.Specialized", "System.Linq", "System.Net"),
globalsType: typeof(ScriptObject)
).GetCompilation();
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
var failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error).Select(s => s.GetMessage());
return (new { Success = false, ErrorMessage = failures });
}
}
}
catch (Exception e)
{
return (new { Success = false, ErrorMessage = e.Message });
}
return (new { Success = true });
}
如果我运行简单代码,则测试通过OK
但是如果我在代码中添加一个方法/函数,我会得到一个异常。例如:
int Add(int x, int y) {
return x+y;
};
Add(1, 4)
我收到错误
预期,方法或访问器块之后的分号无效,只能将赋值,调用,递增,递减和新对象表达式用作语句
错误在"返回x + y;"句子,如果我加上" int c = x + y;"我收到了该行的错误
预计它会起作用,不是吗?