![](/img/trans.png)
[英]How to get Typescript as either FileCodeModel or (Roslyn) Document with working GetSyntaxRoot in VSIX
[英]calling Roslyn from VSIX command
從EnvDTE.ProjectItem獲取Roslyn的SyntaxTree的最佳方法是什么? 我找到了另一種方法(Roslyn的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);
}
弗蘭克的回答很有效。 我發現很難弄清楚類型名稱是什么,所以這里是Frank的完全限定類型名稱的代碼:
using System.Linq;
var dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
var activeDocument = dte?.ActiveDocument;
if (activeDocument != null)
{
var componentModel = (Microsoft.VisualStudio.ComponentModelHost.IComponentModel)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.ComponentModelHost.SComponentModel));
var workspace = (Microsoft.CodeAnalysis.Workspace)componentModel.GetService<Microsoft.VisualStudio.LanguageServices.VisualStudioWorkspace>();
var documentId = workspace.CurrentSolution.GetDocumentIdsWithFilePath(activeDocument.FullName).FirstOrDefault();
if (documentId != null)
{
var document = workspace.CurrentSolution.GetDocument(documentId);
}
}
以下是查找這些類型的參考:
我希望這兩個框架引用可以用對VSSDK.DTE和VSSDK.ComponentModelHost的 NuGet引用替換,但是當我嘗試時,它給出了關於程序集版本不匹配的構建警告,所以我放棄了。
如果你可以弄清楚如何從ProjectItem
到編輯器ITextSnapshot
,那么最好使用snapshot.AsText().GetOpenDocumentInCurrentContextWithChanges()
。
另請注意,在上面的代碼中,通過使用TryGetSyntaxTree
您依賴於其他已請求解析樹的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.