[英]CsScript with Mono: How to make mono not treat warnings as errors
我使用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 { 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編譯器忽略警告。 這是我嘗試過的(基於Mono編譯器的編譯器開關文檔:
CSScript.GlobalSettings.DefaultArguments = "-warn:0 -warnaserror-";
但是我沒有成功,我什至不確定這是否是正確的方法。 無論如何,為了完整起見,我在這里注意到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中執行的內置程序集緩存。 不過,緩存已編譯的腳本對象非常容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.