【问题标题】:CSharpCodeProvider doesn't return compiler warnings when there are no errors没有错误时,CSharpCodeProvider 不会返回编译器警告
【发布时间】:2011-03-03 05:20:02
【问题描述】:

我正在使用CSharpCodeProvider 类来编译我在我的应用程序中用作DSL 的C# 脚本。当有警告但没有错误时,生成的CompilerResults 实例的Errors 属性不包含任何项目。但是当我引入错误时,警告也会突然出现在 Errors 属性中。

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

【问题讨论】:

标签: c# .net compilation compiler-construction .net-4.0


【解决方案1】:

你没有设置CompilerParameters.WarningLevel

【讨论】:

  • 我已经尝试过了,但没有任何区别。此外,如果至少存在错误,则会报告警告。如果警告级别设置为不适当的级别,则不会发生这种情况。
  • 所以事实证明你是对的,我不得不将警告级别设置为 3(我想我只尝试了 0、1 甚至 2)。因为你是第一个提出这个建议的,所以我接受了你的回答。
  • @Sandor:谢谢!据我所知,Reflector WarningLevel 默认设置为4。但在 MSDN 中并没有提到这一点,
【解决方案2】:

在我修复了代码中的其他编译错误(注释字符)并设置 compilerParameters.WarningLevel 之后,它对我来说很好。

【讨论】:

  • 谢谢,在这种情况下将其设置为 3 似乎可以解决问题。我认为很奇怪,如果出现一个或多个错误,无论警告级别参数值如何,都会显示警告。
猜你喜欢
  • 1970-01-01
  • 2014-03-19
  • 1970-01-01
  • 2018-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
相关资源
最近更新 更多