Access/Find 运行时 EnvDTE 文档中的所有变量(Visual Studio/C#/Extension)

Access/Find all variables in an EnvDTE Document at Runtime (Visual Studio/C#/Extension)

我搜索了很长时间,但没有找到任何具体的信息。

我为 Visual Studio 编写了一个扩展,并希望在打开的项目中的 ActiveDocument/Code 文档中找到所有 Variables/Properties。有没有 "easy" 的方式获取它们,还是我需要自己搜索它们?

编辑: 我想在打开的文档中收集有关变量的信息。起初我想创建一个列表,我将其绑定到一个列表框,用户可以在其中看到所有使用的变量(和方法参数 - 只需使用以下语法 "Type VarName")。稍后我将提供翻译这些变量的功能并编辑文档以更改为新语言。

我希望我的主题足够具体。

编辑2:Cole Wu - MSFT 的答案标记为解决方案,并在 Cole Wu 的基础上发布了我的解决方案 - MSFT 的回答。

public void FindVariablesInDoc(EnvDTE.TextDocument haystackDoc) {    
    var objEditPt = haystackDoc.StartPoint.CreateEditPoint();
    var tree = CSharpSyntaxTree.ParseText(objEditPt.GetText(haystackDoc.EndPoint));
    var Mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
    var compilation = CSharpCompilation.Create("MyCompilation", syntaxTrees: new[] { tree }, references: new[] { Mscorlib });
    var model = compilation.GetSemanticModel(tree);
    var variables = tree.GetRoot().DescendantNodes().Where(v => v is FieldDeclarationSyntax || v is LocalDeclarationStatementSyntax || v is PropertyDeclarationSyntax || v is ParameterSyntax);
}

Is there an "easy" way to get them or do I need to search for them by myself?

您可以使用roslyn在运行时查找EnvDTE文档中的所有变量,请参考以下示例代码(请通过Nuget安装Microsoft.CodeAnalysis)。

DTE2 dte = this.ServiceProvider.GetService(typeof(DTE)) as DTE2;
EnvDTE.Document doc = dte.ActiveDocument;
EnvDTE.TextDocument tdoc = (EnvDTE.TextDocument)doc.Object("TextDocument");
EnvDTE.EditPoint objEditPt = tdoc.StartPoint.CreateEditPoint();
string text = objEditPt.GetText(tdoc.EndPoint);
SyntaxTree tree = CSharpSyntaxTree.ParseText(text);

IEnumerable<SyntaxNode> nodes = ((CompilationUnitSyntax)tree.GetRoot()).DescendantNodes();

List<LocalDeclarationStatementSyntax> variableDeclarationList = nodes
                .OfType<LocalDeclarationStatementSyntax>().ToList();