从 VSIX 命令调用 Roslyn

2024-04-15

从 EnvDTE.ProjectItem 获取 Roslyn 的 SyntaxTree 的最佳方法是什么?我找到了另一种方法(Roslyn's Document into ProjectItem)。

我从打开的文档中调用了 VSIX 命令,我想在那里尝试 Roslyn 的语法树。

这段代码有效,但对我来说看起来很尴尬:

    var pi = GetProjectItem();
    var piName = pi.get_FileNames(1);

    var componentModel = (IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(SComponentModel));
    var workspace = componentModel.GetService<Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>();
    var ids = workspace.GetOpenDocumentIds();
    var id1 = ids.First(id => workspace.GetFilePath(id) == piName);

        Microsoft.CodeAnalysis.Solution sln = workspace.CurrentSolution;
        var doc = sln.GetDocument(id1);
        //var w = await doc.GetSyntaxTreeAsync();
        Microsoft.CodeAnalysis.SyntaxTree syntaxTree;
        if (doc.TryGetSyntaxTree(out syntaxTree))

有没有更好的方法从活动文档中获取 Roslyn 的文档?


您可以使用workspace.CurrentSolution.GetDocumentIdsWithFilePath() 来获取与文件路径匹配的DocumentId。从那里你可以使用workspace.CurrentSolution.GetDocument()获取文档本身

private Document GetActiveDocument()
{
    var dte = Package.GetGlobalService(typeof(DTE)) as DTE;
    var activeDocument = dte?.ActiveDocument;
    if (activeDocument == null) return null;

    var componentModel = (IComponentModel)Package.GetGlobalService(typeof(SComponentModel));
    var workspace = (Workspace) componentModel.GetService<VisualStudioWorkspace>();

    var documentid = workspace.CurrentSolution.GetDocumentIdsWithFilePath(activeDocument.FullName).FirstOrDefault();
    if (documentid == null) return null;

    return workspace.CurrentSolution.GetDocument(documentid);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 VSIX 命令调用 Roslyn 的相关文章

随机推荐