C# to format (indent, align) C# properly

前端 未结 6 1897
心在旅途
心在旅途 2021-01-02 16:17

We have a code generator that munges the schema of a given database to automate our inhouse n-tier architecture. The output is various C# partial classes, one per file.

6条回答
  •  悲&欢浪女
    2021-01-02 16:54

    To properly indent code programmatically you would need Microsoft.CodeAnalysis.CSharp nuget package and .NET framework 4.6+. Sample code:

    public string ArrangeUsingRoslyn(string csCode) {
        var tree = CSharpSyntaxTree.ParseText(csCode);
        var root = tree.GetRoot().NormalizeWhitespace();
        var ret = root.ToFullString();
        return ret;
    }
    

    One-liner:

    csCode = CSharpSyntaxTree.ParseText(csCode).GetRoot().NormalizeWhitespace().ToFullString();
    

    You may also use NArrange to sort methods in your cs file, organize usings, create regions, etc. Note that NArrange does not indent anything.

提交回复
热议问题