繁体   English   中英

从Visual Studio扩展中的ProjectItem获取Roslyn SemanticModel

[英]Getting Roslyn SemanticModel from ProjectItem in Visual Studio extension

我正在编写一个Visual Studio 2015扩展,它查看用户右键单击的类的内容。

我有ProjectItem ,但是如何从中获取SemanticModel (和SyntaxTree )?

我需要查找文件中声明的某些类型的属性。 我编写了一个代码分析器,它为您提供了上下文中的SemanticModel ,但我无法弄清楚如何在此处获取它。 搜索没有发现任何有用的东西。 我已经找到了如何通过读取文件内容来解析SyntaxTree ,但是使用SemanticModel并不是那么容易。 理想情况下,我会挂钩VS已经为该文件构建的模型。

弄清楚了。

  1. 将项目升级到目标.NET Framework 4.6.2。
  2. 安装Microsoft.VisualStudio.LanguageServices NuGet包
  3. 将System.Collections.Immutable从1.2.0降级到1.1.37,否则稍后会在代码中收到MissingMethodException。
  4. 在包类的Initialize方法中,获取VisualStudioWorkspace。 我将它保存在静态属性中以便稍后获取:

     var componentModel = (IComponentModel)this.GetService(typeof(SComponentModel)); VisualStudioWorkspace = componentModel.GetService<VisualStudioWorkspace>(); 

现在,您可以从文件路径获取带有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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM