0

我使用 CSScriptLibrary.dll 在 Windows 和 Linux 上运行的应用程序中执行 C# 代码。问题是,现在,我需要使用#pragma disable warning禁用可能出现的各种警告,以便让脚本在 Mono 上编译,这是一个非常丑陋的 hack。

// 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 的默认编译器参数来指示单声道编译器忽略警告。这是我尝试过的(基于 Mono 编译器的编译器开关的文档:

CSScript.GlobalSettings.DefaultArguments = "-warn:0 -warnaserror-";

但我没有成功,我什至不确定这是否是正确的方法。无论如何,为了完整起见,我在这里注意到CSScript.GlobalSettings.DefaultArguments默认为/c /sconfig /co:/warn:0CSScript。

有谁知道如何CSScript.LoadCode忽略 Mono 上的警告,或者至少不将它们视为错误?

4

1 回答 1

0

这里有两个解决方案(在 Oleg Shilo 的帮助下找到)。您可以直接在脚本中包含所需的编译器选项:

//css_co -warn:0 
using System;
...

或者您可以替换CSScript.LoadCodeLoadWithConfig,它允许直接传递编译器选项。像这样的东西:

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 中执行的内置程序集缓存。不过,缓存已编译的脚本对象很容易。

于 2017-04-03T05:46:54.883 回答