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

San*_*zen 6 .net c# compiler-construction compilation .net-4.0

我正在使用CSharpCodeProvider该类编译一个C#脚本,我在我的应用程序中用作DSL.如果有警告但没有错误,Errors则生成的CompilerResults实例的属性不包含任何项目.但是当我引入错误时,警告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);
}
Run Code Online (Sandbox Code Playgroud)

那么如果没有错误,我怎么能得到警告呢?顺便说一句,我不希望设置TreatWarningsAsErrorstrue.

aba*_*hev 1

你没设置CompilerParameters.WarningLevel