C# CsScript with Mono:如何使Mono不将警告视为错误
我使用CSScriptLibrary.dll在运行于Windows和Linux的应用程序中执行C#代码。问题是,现在,我需要使用C# CsScript with Mono:如何使Mono不将警告视为错误,c#,mono,cs-script,C#,Mono,Cs Script,我使用CSScriptLibrary.dll在运行于Windows和Linux的应用程序中执行C#代码。问题是,现在,我需要使用#pragma disable warning来禁用可能出现的各种警告,以便让脚本在Mono上编译,这是一种非常丑陋的攻击 // the following simple script will not execute on Mono due to a warning that a is not used. var code = "public class Script
#pragma disable warning
来禁用可能出现的各种警告,以便让脚本在Mono上编译,这是一种非常丑陋的攻击
// the following simple script will not execute on Mono due to a warning that a is not used.
var code = "public class Script { public object Run() { var a=1; return 2+3; }}"
// here is how the script is executed using CsScriptLibrary
try
{
var asm = new AsmHelper(CSScript.LoadCode(code, "cs", null, true));
// if we reach that point, the script compiled
var obj = asm.CreateAndAlignToInterface<IScript>("*");
// now run it:
var result=obj.Run();
}
catch (CompilerException e)
{
// on .net compiler exceptions are only raised when there are errors
// on mono I get an exception here, even for warnings like unused variable
}
但是我没有成功,我甚至不确定这是不是正确的道路。无论如何,为了完整起见,我在这里注意到,CSScript中的CSScript.GlobalSettings.DefaultArguments
默认为/c/sconfig/co:/warn:0
有人知道如何让CSScript.LoadCode忽略Mono上的警告或至少不将其视为错误吗?这里有两种解决方案(在Oleg Shilo的帮助下找到)。您可以在脚本中直接包含所需的编译器选项:
//css_co -warn:0
using System;
...
或者您可以将CSScript.LoadCode
替换为LoadWithConfig
,这允许直接传递编译器选项。大概是这样的:
static public Assembly LoadCode(string scriptText, bool debugBuild, params string[] refAssemblies)
{
string tempFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() +".cs";
try
{
using (StreamWriter sw = new StreamWriter(tempFile))
sw.Write(scriptText);
return LoadWithConfig(scriptFile, null, debugBuild, CSScript.GlobalSettings, "-warn:0", refAssemblies);
}
finally
{
if (!debugBuild)
{
//delete temp file
}
}
}
应该注意的是,第二个解决方案将绕过在LoadCode中执行的内置程序集缓存。不过,缓存已编译的脚本对象很容易
static public Assembly LoadCode(string scriptText, bool debugBuild, params string[] refAssemblies)
{
string tempFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() +".cs";
try
{
using (StreamWriter sw = new StreamWriter(tempFile))
sw.Write(scriptText);
return LoadWithConfig(scriptFile, null, debugBuild, CSScript.GlobalSettings, "-warn:0", refAssemblies);
}
finally
{
if (!debugBuild)
{
//delete temp file
}
}
}