从 TypeSyntax 获取 SyntaxTree

Get SyntaxTree from TypeSyntax

有没有一种简单的方法可以找到定义了特定 TypeSyntax 的文档的 SyntaxTree

每当 TypeSyntaxIdentifierNameSyntax 时,我可以获得 Identifier 属性,但我仍然无法通过安全方式访问 SyntaxTree类型。

更新:

这是我目前拥有的:

var right = exp.Right as ObjectCreationExpressionSyntax;
                    if (right != null) {
                        Compilation comp;
                        if ((comp = activeProject.GetCompilationAsync().Result) != null) {
                            bool cst = comp.ContainsSyntaxTree(right.Type.SyntaxTree);
                            var semanticModel = comp.GetSemanticModel(right.Type.SyntaxTree);
                            var typeInfo = semanticModel.GetTypeInfo(right.Type);
                            Console.WriteLine();
                            //var c = comp.GetSemanticModel(comp);
                            //var model = c.GetTypeInfo(right.Type as TypeSyntax);
                            //var v = model.Type.DeclaringSyntaxReferences;
                        }
                    }

要读取类型信息,您需要获取语义模型。

调用SemanticModel.GetSymbolInfo(TypeSyntax)获取SymbolInfo,然后读取符号DeclaringSyntaxReferences property

请注意,部分 类 可能在多个文件中定义了多个符号。