问题描述
我正在尝试使用Roslyn来确定项目的公开API(然后使用此信息进行一些进一步的处理,因此我不能仅使用反射)。我正在使用SyntaxWalker访问声明语法节点,并为每个节点调用IModel.GetDeclaredSymbol。这对于方法,属性和类型似乎效果很好,但似乎不适用于字段。我的问题是,如何获取FieldDeclarationSyntax节点的FieldSymbol?
I'm trying to use Roslyn to determine the publically-exposed API of a project (and then do some further processing using this information, so I can't just use reflection). I'm using a SyntaxWalker to visit declaration syntax nodes, and calling IModel.GetDeclaredSymbol for each. This seems to work well for Methods, Properties, and Types, but it doesn't seem to work on fields. My question is, how do I get the FieldSymbol for a FieldDeclarationSyntax node?
这是我正在使用的代码:
Here's the code I'm working with:
public override void VisitFieldDeclaration(FieldDeclarationSyntax node)
{
var model = this._compilation.GetSemanticModel(node.SyntaxTree);
var symbol = model.GetDeclaredSymbol(node);
if (symbol != null
&& symbol.CanBeReferencedByName
// this is my own helper: it just traverses the publ
&& symbol.IsExternallyPublic())
{
this._gatherer.RegisterPublicDeclaration(node, symbol);
}
base.VisitFieldDeclaration(node);
}
推荐答案
您需要记住字段声明语法可以声明多个字段。因此,您需要:
You need to remember that a field declaration syntax can declare multiple fields. So you want:
foreach (var variable in node.Declaration.Variables)
{
var fieldSymbol = model.GetDeclaredSymbol(variable);
// Do stuff with the symbol here
}
这篇关于如何从FieldDeclarationSyntax节点获取Roslyn FieldSymbol?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!