创建新节点时注释会发生什么?

时间:2013-11-06 15:38:44

标签: c# roslyn

我得到了一个关于我的注释已经消失的问题的答案(Where is my annotation?),并且我已经重读了20次,但我仍然不清楚为什么这段代码不起作用,为什么我无法获得带注释的属性,问题出在哪里。我已经内联了代码,以便更容易阅读...

SyntaxAnnotation propertyAnnotation = null;
SyntaxAnnotation classAnnotation = null;

//first annotate class
classAnnotation = new SyntaxAnnotation();

var newRoot = document.GetSyntaxRoot()
                .ReplaceNode(classDeclaration, classDeclaration.WithAdditionalAnnotations(classAnnotation));

document = document.UpdateSyntaxRoot(newRoot);

//now annotate property 
//first look for classNode that was annotated in previous step
var classNode = document.GetAnnotatedNode<ClassDeclarationSyntax>(classAnnotation);

//now annotate property
propertyAnnotation = new SyntaxAnnotation();
var newClassNode = classNode.ReplaceNode(propertyDeclaration, propertyDeclaration.WithAdditionalAnnotations(propertyAnnotation));

newRoot = document.GetSyntaxRoot()
                     .ReplaceNode(classNode, newClassNode);

document = document.UpdateSyntaxRoot(newRoot);

//Works 
newClassNode = document.GetAnnotatedNode<ClassDeclarationSyntax>(classAnnotation);

//Fails here????
var newPropertyNode = document.GetAnnotatedNode<PropertyDeclarationSyntax>(propertyAnnotation);

1 个答案:

答案 0 :(得分:0)

问题在于:

var newClassNode = classNode.ReplaceNode(propertyDeclaration, propertyDeclaration.WithAdditionalAnnotations(propertyAnnotation));

因为您已注释了类声明,所以在该调用中永远不会找到propertyDeclaration。它是具有原始classDeclaration的树的一部分,而不是带注释的树。将注释添加到propertyDeclaration后,您应该重新找到classDeclaration