C# 在更改SyntaxTree后,如何在Roslyn中更新SemanticModel?
我试图在Roslyn中执行语法转换。AST重排工作正常,但是,在我更改内容时,我需要得到一个更新的C# 在更改SyntaxTree后,如何在Roslyn中更新SemanticModel?,c#,.net,abstract-syntax-tree,roslyn,C#,.net,Abstract Syntax Tree,Roslyn,我试图在Roslyn中执行语法转换。AST重排工作正常,但是,在我更改内容时,我需要得到一个更新的语义模型,它反映了我的语法树的新结构 改造树木 这部分工作正常,我可以说,因为我已经做了大量调试 CSharpSyntaxTree tree = RetrieveTree(); // Just successfully gets the original tree CSharpCompilation compilation = CSharpCompilation.Create(...); // Re
语义模型,它反映了我的语法树的新结构
改造树木
这部分工作正常,我可以说,因为我已经做了大量调试
CSharpSyntaxTree tree = RetrieveTree(); // Just successfully gets the original tree
CSharpCompilation compilation = CSharpCompilation.Create(...); // Retrieves the compilation object
CompilationUnitSyntax node = tree.GetRoot();
// Doing stuff to change the tree
node = node.RemoveNodes(...);
node = node.AddMembers(...);
这样我就可以得到新的树:
CSharpSyntaxTree newTree = node.SyntaxTree as CSharpSyntaxTree;
通过调试,我可以看到newTree
具有新的结构,而tree
具有旧的结构。我还可以成功地遍历newTree
并在AST上操作。因此,转型是成功的
更新树和语义
当我尝试更新csharp编译时,当我从中获得语义模型时,我认为问题从这里开始
CSharpCompilation newCompilation = compilation.ReplaceSyntaxTree(tree, newTree);
SemanticModel newSemanticModel = newCompilation.GetSemanticModel(newTree);
因为当我尝试时:
TypeSyntax myClassTypeNode = GetSourceCodeClassTypeNode(); // Just successfully gets a node
var symbol = newSemanticModel.getSymbolInfo(myClassTypeNode).Symbol;
然后符号
为空。当然,如果我尝试使用原始的SemanticModel
,它也会保持为null
如果不执行转换并使用旧的语义模型
,符号将成功检索
我做错了什么?试试newSemanticModel.GetDeclaredSymbol(myClassTypeName)@DudiKeleti:Alwaysnull
。关键是,我认为问题不在于getSymbolInfo
,因为它在没有转换的情况下工作。问题是我没有以正确的方式更新SemanticModel
。似乎是您做了替换。我马上去看看。还有一件事,你检查过编译错误吗?编译。GetDiagnostics()@DudiKeleti:哦,该死的。。。当然我正在重新安排一切,所以在引用东西时会出现问题。我实际上正在将类移动到新的名称空间中,所以。。。这就是问题所在!