Obtaining the type under the cursor? #400
-
I am trying to write a command that mimics what Rider does in var query = new QueryForPerson(name: "Gringo");
var result = await _mediator.Send(query, cancellationToken); What I'd like my extension to do is when I have the cursor on the Thsi is my first time writing an extension for VS2022, I've watched @madskristensen s video introduction, and fell short immediately as the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
First, you'll need to install the Then you can get the document in Roslyn like this: // Get the workspace.
Workspace workspace = await VS.GetMefServiceAsync<VisualStudioWorkspace>();
// Get the active Visual Studio document.
DocumentView? documentView = await VS.Documents.GetActiveDocumentViewAsync();
if (document is not null) {
// Get the Roslyn document for that file.
DocumentId? id = workspace.CurrentSolution.GetDocumentIdsWithFilePath(documentView.FilePath).FirstOrDefault();
if (id is not null) {
Document roslynDocument = workspace.CurrentSolution.GetDocument(id);
}
} If you know your way around Roslyn, then it's probably not too difficult to get the type at the cursor. I haven't tried this, but it might point you in the right direction. // Get the selection.
int position = documentView.TextView.Selection.ActivePoint.Position.Position;
// Get the syntax root.
SyntaxNode root = await roslynDocument.GetSyntaxRootAsync();
// Find the node at the selection.
SyntaxNode selectedNode = root.FindNode(new TextSpan(position, 1));
// Get the type information for that node.
SemanticModel model = await roslynDocument.GetSemanticModelAsync();
TypeInfo typeInfo = model.GetTypeInfo(node); |
Beta Was this translation helpful? Give feedback.
First, you'll need to install the
Microsoft.VisualStudio.LanguageServices
NuGet package.Then you can get the document in Roslyn like this:
If you know your way around Roslyn, …