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

Ran*_*ngy 4 c# vsx visual-studio roslyn visual-studio-2015

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

我已经得到了ProjectItem,但是你如何从中得到SemanticModel( 和) 呢?SyntaxTree

我需要查找文件中声明的某些类型的属性。我编写了一个代码分析器,它可以为您提供SemanticModel上下文,但我不知道如何在这里获取它。搜索没有发现任何有用的东西。我已经找到了如何SyntaxTree通过读取文件内容来解析 ,但对于SemanticModel. 理想情况下,我会连接到 VS 已经为该文件构建的模型。

Ran*_*ngy 5

弄清楚了。

  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>();
    
    Run Code Online (Sandbox Code Playgroud)

现在您可以从文件路径获取包含 SyntaxTree 和 SemanticModel 的文档:

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();
Run Code Online (Sandbox Code Playgroud)