从 VSIX 命令调用 Roslyn [英] calling Roslyn from VSIX command
问题描述
从 EnvDTE.ProjectItem 获取 Roslyn 的 SyntaxTree 的最佳方法是什么?我找到了另一种方法(Roslyn's Document into ProjectItem).
What is best way to obtain Roslyn's SyntaxTree from EnvDTE.ProjectItem? I found some method for the other way (Roslyn's Document into ProjectItem).
我从打开的文档中调用了 VSIX 命令,我想在那里试验 Roslyn 的语法树.
I got VSIX command called from opened document and I'd like to experiment with Roslyn's syntax tree there.
此代码有效,但对我来说看起来很尴尬:
This code works, but looks awkward to me:
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 的文档?
Is there better way to get Roslyn's Document from active document?
推荐答案
您可以使用 workspace.CurrentSolution.GetDocumentIdsWithFilePath() 获取与文件路径匹配的 DocumentId.从中您可以使用 workspace.CurrentSolution.GetDocument()
You can use workspace.CurrentSolution.GetDocumentIdsWithFilePath() to get the DocumentId(s) matching a file path. From that you can get the document itself using 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);
}
这篇关于从 VSIX 命令调用 Roslyn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!