在 roslyn 中对解决方案应用多项更改

Applying multiple changes to a solution in roslyn

我想对一个解决方案的多个文档应用更改,但只有第一个更改被反映出来,其余的被拒绝。This link 说明如何只能对一个更改应用一次解决方案。解决这个问题的方法是什么。如果 link 指向解决方案或代码片段,我将不胜感激。

这是我的功能:

public static async Task<bool> AddMethod(string solutionPath)
{
    var workspace = MSBuildWorkspace.Create(); 
    var solution = await workspace.OpenSolutionAsync(solutionPath);
    ClassDeclarationSyntax cls = SyntaxFactory.ClassDeclaration("someclass");

    foreach (var project in solution.Projects)
    {
        foreach(var document in project.Documents)
        {
            Document doc = project.GetDocument(document.Id);
            var root = await doc.GetSyntaxRootAsync();
            var classes = root.DescendantNodes().Where(n => n.IsKind(SyntaxKind.ClassDeclaration));
            if (classes.Count() != 0)
            {
                SyntaxNode FirstClass = classes.First() as ClassDeclarationSyntax;
                if (FirstClass != null)
                {
                    var newRoot = root.ReplaceNode(FirstClass, cls);
                    doc = doc.WithText(newRoot.GetText());
                    Project proj = doc.Project;
                    var abc = workspace.TryApplyChanges(proj.Solution);
                }
            }
        }
    }
    return true;
}

解决方法是使用 ProjectIdDocumentId 并一次性将所有更改应用到工作区。

尝试以下操作:

public static async Task<bool> AddMethod(string solutionPath)
{
    var workspace = MSBuildWorkspace.Create();
    var solution = await workspace.OpenSolutionAsync(solutionPath);
    ClassDeclarationSyntax cls = SyntaxFactory.ClassDeclaration("someclass");

    foreach (var projectId in solution.ProjectIds)
    {
        var project = solution.GetProject(projectId);
        foreach (var documentId in project.DocumentIds)
        {
            Document doc = project.GetDocument(documentId);
            var root = await doc.GetSyntaxRootAsync();
            var firstClass = root.DescendantNodes().OfType<ClassDeclarationSyntax>().FirstOrDefault();
            if (firstClass == null)
                return true;

            var newRoot = root.ReplaceNode(firstClass, cls);
            doc = doc.WithText(newRoot.GetText());
            //Persist your changes to the current project
            project = doc.Project;
        }

        //Persist the project changes to the current solution
        solution = project.Solution;
    }
    //Finally, apply all your changes to the workspace at once.
    var abc = workspace.TryApplyChanges(solution);
    return true;
}