C# CSharpCodeProvider没有';t在没有错误时返回编译器警告
我正在使用C# CSharpCodeProvider没有';t在没有错误时返回编译器警告,c#,.net,compilation,compiler-construction,.net-4.0,C#,.net,Compilation,Compiler Construction,.net 4.0,我正在使用CSharpCodeProvider类编译一个C#脚本,在我的应用程序中用作DSL。当存在警告但没有错误时,生成的CompilerResults实例的errors属性不包含任何项。但是当我引入错误时,警告也会突然出现在Errors属性中 string script = @" using System; using System; // generate a warning namespace MyNamespace { public cl
CSharpCodeProvider
类编译一个C#脚本,在我的应用程序中用作DSL。当存在警告但没有错误时,生成的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);
}
string脚本=@”
使用制度;
使用System;//生成警告
名称空间MyNamespace
{
公共类MyClass
{
公共方法()
{
//取消注释下一条语句以生成错误
//intx=0;
}
}
}
";
CSharpCodeProvider provider=新的CSharpCodeProvider(
新字典()
{
{“CompilerVersion”,“v4.0”}
});
CompilerParameters CompilerParameters=新的CompilerParameters();
compilerParameters.GenerateExecutable=false;
compilerParameters.GenerateInMemory=true;
CompilerResults results=provider.CompileAsemblyFromSource(
编译器参数,
剧本);
foreach(结果中的编译器错误。错误)
{
控制台。写入(error.IsWarning?“警告::”错误:);
Console.WriteLine(error.ErrorText);
}
那么,在没有错误的情况下,如何获得警告呢?
顺便说一句,我不想将
treatwarningaserrors
设置为true
您没有设置编译器参数。在我修复了代码中的其他编译错误(注释字符)并设置编译器参数之后,WarningLevel
对我来说效果很好,请参见《关于生成InMemory》
@abatishchev谢谢,这是一个有趣的事实。我已经试过了,但没有任何区别。此外,如果至少存在错误,则会报告警告。如果将警告级别设置为不适当的级别,则不会发生这种情况。因此,事实证明,您是对的。毕竟,我必须将警告级别设置为3(我想我只尝试了0、1或2)。因为你是第一个提出这个建议的,所以我接受了你的回答。@Sandor:谢谢!据我所知,Reflector警告级别默认设置为4
。但是在MSDN中没有提到这一点,谢谢,在这种情况下,将其设置为3似乎可以起到作用。我认为奇怪的是,在一个或多个错误的情况下,无论警告级别参数值如何,警告都会显示出来。