如何使用Roslyn枚举VB文档中的成员(命名空间、类等)详细信息? [英] Using Roslyn, how to enumerate members (Namespaces, classes etc) details in Visual Basic Document?

查看:0
本文介绍了如何使用Roslyn枚举VB文档中的成员(命名空间、类等)详细信息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Roslyn,确定Visual Basic文档成员的唯一机制似乎是:

var members = SyntaxTree.GetRoot().DescendantNodes().Where(node =>
      node is ClassStatementSyntax ||
      node is FunctionAggregationSyntax ||
      node is IncompleteMemberSyntax ||
      node is MethodBaseSyntax ||
      node is ModuleStatementSyntax ||
      node is NamespaceStatementSyntax ||
      node is PropertyStatementSyntax ||
      node is SubNewStatementSyntax
    );

如何获取每个成员的成员nameStarLineNumberEndLineNumber

推荐答案

不仅存在获取它的唯一方式:

1)正如您所尝试的:我不会为所有种类的成员显示这种方式(他们的数量很大,逻辑相似),但只显示其中的一个,例如ClassStatementSyntax

  • 要实现它的名称,只需获取ClassStatementSyntax.Identifier.ValueText
  • 要获得起始行,您可以使用Location方法之一:
var location = Location.Create(SyntaxTree, ClassStatementSyntax.Identifier.Span);
var startLine = location.GetLineSpan().StartLinePosition.Line;
  • 检索结束行的逻辑看起来像是接收开始行的逻辑,但它依赖于相应的结束语句(某种结束语句或自身)
2)更有用的方法-使用SemanticModel获取所需数据: 这样,您只需要接收ClassStatementSyntaxModuleStatementSyntxtNamespaceStatementSyntax的语义信息,只需调用GetMembers()

即可接收其所有成员
...

  SemanticModel semanticModel = // usually it is received from the corresponding compilation
  var typeSyntax = // ClassStatementSyntax, ModuleStatementSyntxt or NamespaceStatementSyntax
  string name = null;
  int startLine;
  int endLine;

  var info = semanticModel.GetSymbolInfo(typeSyntax);
  if (info.Symbol is INamespaceOrTypeSymbol typeSymbol)
  {
      name = typeSymbol.Name; // retrieve Name
      startLine = semanticModel.SyntaxTree.GetLineSpan(typeSymbol.DeclaringSyntaxReferences[0].Span).StartLinePosition.Line; //retrieve start line
      endLine = semanticModel.SyntaxTree.GetLineSpan(typeSymbol.DeclaringSyntaxReferences[0].Span).EndLinePosition.Line; //retrieve end line
      foreach (var item in typeSymbol.GetMembers())
      {
          // do the same logic for retrieving name and lines for all others members without calling GetMembers()
      }
  }
  else if (semanticModel.GetDeclaredSymbol(typeSyntax) is INamespaceOrTypeSymbol typeSymbol2)
  {
      name = typeSymbol2.Name; // retrieve Name
      startLine = semanticModel.SyntaxTree.GetLineSpan(typeSymbol2.DeclaringSyntaxReferences[0].Span).StartLinePosition.Line; //retrieve start line
      endLine = semanticModel.SyntaxTree.GetLineSpan(typeSymbol2.DeclaringSyntaxReferences[0].Span).EndLinePosition.Line; //retrieve end line

      foreach (var item in typeSymbol2.GetMembers())
      {
          // do the same logic for retrieving name and lines for all others members without calling GetMembers()
      }
  }

但请注意,当您有部分声明时,您的DeclaringSyntaxReferences将有几个项,因此您需要根据您的当前SyntaxTree

进行筛选

这篇关于如何使用Roslyn枚举VB文档中的成员(命名空间、类等)详细信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆