我想将更改应用于解决方案的多个文档,但只反映了第一个更改,其余部分被拒绝。This链接显示了只有一次更改应用于解决方案。这将是一个什么样的解决方案。我希望链接指向解决方案或代码段。
这是我的功能:
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;
}
答案 0 :(得分:7)
解决方法是使用ProjectId
和DocumentId
并一次将所有更改应用到工作区。
尝试以下方法:
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;
}