我使用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
。
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
@abatishchev谢谢,这是一个有趣的事实。 – 2010-06-13 13:40:49