[英]Getting Roslyn SemanticModel from ProjectItem in Visual Studio extension
I'm writing a Visual Studio 2015 extension which looks at the contents of the class the user has right clicked on. 我正在编写一个Visual Studio 2015扩展,它查看用户右键单击的类的内容。
I've got the ProjectItem
, but how do you get the SemanticModel
(and SyntaxTree
) from this? 我有
ProjectItem
,但是如何从中获取SemanticModel
(和SyntaxTree
)?
I need to look up some types of properties declared in the file. 我需要查找文件中声明的某些类型的属性。 I've written a code analyzer which gives you the
SemanticModel
on the context but I can't figure out how to get it here. 我编写了一个代码分析器,它为您提供了上下文中的
SemanticModel
,但我无法弄清楚如何在此处获取它。 Searches haven't turned up anything useful. 搜索没有发现任何有用的东西。 I've found how to parse the
SyntaxTree
by reading the file contents, but it won't be so easy with the SemanticModel
. 我已经找到了如何通过读取文件内容来解析
SyntaxTree
,但是使用SemanticModel
并不是那么容易。 Ideally I'd hook in to the model VS has already built for the file. 理想情况下,我会挂钩VS已经为该文件构建的模型。
Figured it out. 弄清楚了。
In the package class's Initialize
method, grab the VisualStudioWorkspace. 在包类的
Initialize
方法中,获取VisualStudioWorkspace。 I save it in a static property here to grab later: 我将它保存在静态属性中以便稍后获取:
var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel)); VisualStudioWorkspace = componentModel.GetService<VisualStudioWorkspace>();
Now you can get the Document with SyntaxTree and SemanticModel from the file path: 现在,您可以从文件路径获取带有SyntaxTree和SemanticModel的Document:
Microsoft.CodeAnalysis.Solution solution = CreateUnitTestBoilerplateCommandPackage.VisualStudioWorkspace.CurrentSolution;
DocumentId documentId = solution.GetDocumentIdsWithFilePath(inputFilePath).FirstOrDefault();
var document = solution.GetDocument(documentId);
SyntaxNode root = await document.GetSyntaxRootAsync();
SemanticModel semanticModel = await document.GetSemanticModelAsync();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.