C#Roslyn API,读取一个.cs文件,更新一个类,写回到.cs文件

前端之家收集整理的这篇文章主要介绍了C#Roslyn API,读取一个.cs文件,更新一个类,写回到.cs文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个工作代码,将.cs文件加载到Roslyn SyntaxTree类中,创建一个新的PropertyDeclarationSyntax,将其插入到类中,并重新写入.cs文件.我正在做这个学习经验以及一些潜在的未来想法.我发现在任何地方似乎都不是一个完整的Roslyn API文档,我不确定我是否有效地执行此操作.我主要关心的是我所说的“root.ToFullString()”,而它的工作原理是这样做的正确方法
using System.IO;
using System.Linq;
using Roslyn.Compilers;
using Roslyn.Compilers.CSharp;

class RoslynWrite
{
    public RoslynWrite()
    {
        const string csFile = "MyClass.cs";

        // Parse .cs file using Roslyn SyntaxTree
        var SyntaxTree = SyntaxTree.ParseFile(csFile);
        var root = SyntaxTree.GetRoot();
        // Get the first class from the Syntax tree
        var myClass = root.DescendantNodes().OfType<ClassDeclarationSyntax>().First();

        // Create a new property : 'public bool MyProperty { get; set; }'
        var myProperty = Syntax.PropertyDeclaration(Syntax.ParseTypeName("bool"),"MyProperty")
                            .WithModifiers(Syntax.Token(SyntaxKind.PublicKeyword))
                            .WithAccessorList(
                            Syntax.AccessorList(Syntax.List(
                                Syntax.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
                                    .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)),Syntax.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
                                    .WithSemicolonToken(Syntax.Token(SyntaxKind.SemicolonToken)))));

        // Add the new property to the class
        var updatedClass = myClass.AddMembers(myProperty);
        // Update the SyntaxTree and normalize whitespace 
        var updatedRoot = root.ReplaceNode(myClass,updatedClass).NormalizeWhitespace();

        // Is this the way to write the Syntax tree? ToFullString?
        File.WriteAllText(csFile,updatedRoot.ToFullString());
    }
}

解决方法

回答Roslyn CTP论坛 in this post

That approach is generally fine,though if you are worried about allocating a string for the text of the entire file,you should probably use IText.Write(TextWriter) instead of ToFullString().

Keep in mind that it’s possible to generate trees that will not round-trip through the parser. For example,if you generated something that violates precedence rules,the SyntaxTree construction APIs won’t catch that.

猜你在找的C&C++相关文章