代码之家  ›  专栏  ›  技术社区  ›  Sandor Drieënhuizen

CSharpCodeProvider在没有错误时不返回编译器警告

  •  6
  • Sandor Drieënhuizen  · 技术社区  · 15 年前

    我正在使用 CSharpCodeProvider 类编译一个C脚本,在应用程序中用作DSL。当出现警告但没有错误时, Errors 结果的属性 CompilerResults 实例不包含任何项。但是当我引入一个错误时,警告会突然出现在 错误 还有财产。

    string script = @"
        using System;
        using System; // generate a warning
        namespace MyNamespace
        {
            public class MyClass
            {
                public void MyMethod()
                {
                    // uncomment the next statement to generate an error
                    //intx = 0;
                }
            }
        }
    ";
    
    CSharpCodeProvider provider = new CSharpCodeProvider(
        new Dictionary<string, string>()
        {
            { "CompilerVersion", "v4.0" }
        });
    
    CompilerParameters compilerParameters = new CompilerParameters();
    compilerParameters.GenerateExecutable = false;
    compilerParameters.GenerateInMemory = true;
    
    CompilerResults results = provider.CompileAssemblyFromSource(
        compilerParameters,
        script);
    
    foreach (CompilerError error in results.Errors)
    {
        Console.Write(error.IsWarning ? "Warning: " : "Error: ");
        Console.WriteLine(error.ErrorText);
    }
    

    那么,在没有错误的情况下,如何获取警告呢? 顺便说一下,我不想 TreatWarningsAsErrors true .

    2 回复  |  直到 8 年前
        1
  •  1
  •   abatishchev Karl Johan    15 年前

    你没有设定 CompilerParameters.WarningLevel

        2
  •  1
  •   Jay Bazuzi Buck Hodges    15 年前

    在我修复了代码中的其他编译错误(注释字符)并设置 compilerParameters.WarningLevel .