使用 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
);
如何获得会员name
, StarLineNumber
and EndLineNumber
每个成员的?
不仅存在一种获得它的方法:
1)当你尝试时:我不会向所有善良的成员展示这种方式(他们的数量很大并且逻辑是相似的),但只展示其中的一个,例如ClassStatementSyntax
:
- 实现它的名字只是得到
ClassStatementSyntax.Identifier.ValueText
- 要获得起始线,您可以使用
Location
作为方式之一:
var location = Location.Create(SyntaxTree, ClassStatementSyntax.Identifier.Span);
var startLine = location.GetLineSpan().StartLinePosition.Line;
- 检索结束行的逻辑看起来像接收开始行的逻辑,但它依赖于相应的结束语句(某种结束语句或 self)
2)更有用的方式——使用SemanticModel
获取您想要的数据:
通过这种方式,您将只需要接收语义信息ClassStatementSyntax
, ModuleStatementSyntxt
and NamespaceStatementSyntax
,只需致电即可收到他们的所有成员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
会有几个项目,所以你需要过滤SyntaxReference
按你当前的SyntaxTree
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)