2010-06-13 79 views
6

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

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

+0

btw,请参阅http://stackoverflow.com/questions/2610886/is-it-possible-to-call-c-lexical-syntactic-analyzers-without-compilation/2611177#2611177关于'GenerateInMemory' – abatishchev 2010-06-13 13:38:44

+0

@abatishchev谢谢,这是一个有趣的事实。 – 2010-06-13 13:40:49

回答

1

您没有设置CompilerParameters.WarningLevel

+0

我已经尝试过了,但没有任何区别。此外,如果至少出现错误,则会报告警报。如果警告级别设置为不适当的级别,则不会发生这种情况。 – 2010-06-13 13:45:28

+0

因此,事实证明你毕竟是正确的,我不得不将警告级别设置为3(我想我只尝试过0,1或者2)。因为你是第一个提出这个建议的人,所以我接受了你的答案。 – 2010-06-14 07:58:29

+0

@Sandor:谢谢!据我所知,反射器“WarningLevel”默认设置为“4”。但在MSDN中没有什么关于这个的, – abatishchev 2010-06-14 11:17:15

1

它的工作对我很好,我以后固定另一个在你的代码(注释字符)编译错误,并将compilerParameters.WarningLevel

+0

谢谢,在这种情况下将它设置为3似乎有伎俩。我认为这是奇怪的,尽管如果出现一个或多个错误,无论警告级别参数值如何,都会显示警告。 – 2010-06-14 07:59:42