从命令行检查C#语法

Mic*_*ael 8 c# vim syntax-checking syntastic

有没有人知道在Microsoft .NET框架中检查给定C#文件的语法和语法的方法?

对于一些小背景,我感兴趣的是设置合成来检查.cs文件的语法.开箱即用,syntastic使用Mono C#编译器及其--parse标志来执行此操作,但我在Microsoft .NET框架中找不到相同的东西.

我第一次尝试使用它是用来csc /target:library /nologo代替mcs --parse,但问题是这是基于每个文件调用的.因此,它报告缺少名称空间(存在于完整项目构建中)而不仅仅是语法错误.

csh*_*net 1

我之前曾在 icsharpcode IDE 中使用过NRefactory 。对于基本的东西来说,它既快速又简单。

请参阅这篇文章: 使用 NRefactory 分析 C# 代码

我使用它从 C# 示例创建 VB.NET 示例。执行此操作的方法非常简单,并且可以轻松适应您的需求:

    private static void ConvertLanguage(TextReader input, TextWriter output, SupportedLanguage language, Action<string> onError)
    {
        using (IParser parser = ParserFactory.CreateParser(language, input))
        {
            parser.Parse();
            var specials = parser.Lexer.SpecialTracker.RetrieveSpecials();
            var result = parser.CompilationUnit;
            //if (parser.Errors.Count > 0)
            //    MessageBox.Show(parser.Errors.ErrorOutput, "Parse errors");

            IOutputAstVisitor outputVisitor;
            if (language == SupportedLanguage.CSharp)
                outputVisitor = new VBNetOutputVisitor();
            else
                outputVisitor = new CSharpOutputVisitor();

            outputVisitor.Options.IndentationChar = ' ';
            outputVisitor.Options.IndentSize = 4;
            outputVisitor.Options.TabSize = 4;

            using (SpecialNodesInserter.Install(specials, outputVisitor))
                result.AcceptVisitor(outputVisitor, null);

            if (outputVisitor.Errors.Count > 0 && onError != null)
                onError(outputVisitor.Errors.ErrorOutput);

            output.Write(outputVisitor.Text);
        }
    }
Run Code Online (Sandbox Code Playgroud)

注意:前面的代码来自旧版本,可能无法针对最新版本的 NRefactory 库进行编译。