如何从SemanticModel为新创建的类获取声明的符号?

时间:2015-09-17 17:56:07

标签: c# roslyn .net-4.6

从我刚刚创建的ISymbol中获取ClassDeclaration的最简单方法是什么?

请考虑以下代码:

AdhocWorkspace workspace = new AdhocWorkspace();         
Project project = workspace.AddProject("Test", LanguageNames.CSharp);

ClassDeclarationSyntax classDeclaration = SyntaxFactory.ClassDeclaration("MyClass");
CompilationUnitSyntax compilationUnit = SyntaxFactory.CompilationUnit().AddMembers(classDeclaration);         
Document document = project.AddDocument("Test.cs", compilationUnit);
SemanticModel semanticModel = await document.GetSemanticModelAsync();
ISymbol symbol = semanticModel.GetDeclaredSymbol(classDeclaration); // <-- Throws Exception

最后一行抛出一个异常,说“语法节点不在语法树中”。

我认为我需要从新的ClassDeclarationSyntax再次获取我刚创建的SyntaxTree。但是,鉴于我只有旧SyntaxTree,在新ClassDeclarationSyntax中找到它的最简单方法是什么?

在上面的示例中,类是SyntaxTree中唯一的类,并且是CompilationUnit的第一个子类,因此在这个简单的情况下很容易找到。但是想象一下语法树包含很多声明的情况,这些声明可能是嵌套的,并且所寻求的类声明嵌套在内部?有没有办法使用旧的ClassDeclarationSyntax找到新的?{1}}? (或者我在这里做错了什么?)

1 个答案:

答案 0 :(得分:8)

您可以使用SyntaxAnnotation来跟踪您的班级节点:

AdhocWorkspace workspace = new AdhocWorkspace();
Project project = workspace.AddProject("Test", LanguageNames.CSharp);

//Attach a syntax annotation to the class declaration
var syntaxAnnotation = new SyntaxAnnotation("ClassTracker");
var classDeclaration = SyntaxFactory.ClassDeclaration("MyClass")
    .WithAdditionalAnnotations(syntaxAnnotation);

var compilationUnit = SyntaxFactory.CompilationUnit().AddMembers(classDeclaration);

Document document = project.AddDocument("Test.cs", compilationUnit);
SemanticModel semanticModel = document.GetSemanticModelAsync().Result;

//Use the annotation on our original node to find the new class declaration
var changedClass = document.GetSyntaxRootAsync().Result.DescendantNodes().OfType<ClassDeclarationSyntax>()
    .Where(n => n.HasAnnotation(syntaxAnnotation)).Single();
var symbol = semanticModel.GetDeclaredSymbol(changedClass);

无论您最终将课程添加到哪种复杂文档,这都应该有效。