gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:47:43 25 4
gpt4 key购买 nike

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

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

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

最佳答案

想通了。

  1. 将您的项目升级到目标 .NET Framework 4.6.2。
  2. 安装 Microsoft.VisualStudio.LanguageServices NuGet package .
  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 的文档:

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();

关于c# - 从 Visual Studio 扩展中的 ProjectItem 获取 Roslyn SemanticModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39132524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com