简体   繁体   English

如何从 FieldDeclarationSyntax 节点获取 Roslyn FieldSymbol?

[英]How to get a Roslyn FieldSymbol from a FieldDeclarationSyntax node?

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).我正在尝试使用 Roslyn 来确定项目公开公开的 API(然后使用此信息做一些进一步的处理,所以我不能只使用反射)。 I'm using a SyntaxWalker to visit declaration syntax nodes, and calling IModel.GetDeclaredSymbol for each.我正在使用 SyntaxWalker 访问声明语法节点,并为每个节点调用 IModel.GetDeclaredSymbol。 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?我的问题是,如何获取 FieldDeclarationSyntax 节点的 FieldSymbol?

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
}

Can I expand on this? 我可以扩展一下吗? I'm fine with the design path they took separating these on the syntactic level. 我对他们在语法层面上将它们分开的设计路径感到满意。 One field can declare several variables. 一个字段可以声明多个变量。

But on the symbol level, I find it confusing that they seem to be merged into a single symbol (ie IFieldSymbol ), when in fact some traits are on the "field as a whole declaration", not on the variable level. 但是在符号级别,我发现将它们似乎合并为单个符号(即IFieldSymbol )感到困惑,因为实际上某些特征在“整个字段声明”上而不是在变量级别上。

Consider IFieldSymbol.IsReadOnly for example. 例如,考虑IFieldSymbol.IsReadOnly When declaring multiple variables as part of a single field declaration, the readonly constraint is on the field level. 在单个字段声明中声明多个变量时,只读约束位于字段级别。 And so is the data type. 数据类型也是如此。 Why would I want to access that information on every possible variable? 我为什么要在每个可能的变量上访问该信息?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM