When to use SemanticModel.GetSymbolInfo and when S

2019-06-15 03:26发布

问题:

In some cases, when I'm trying to get the the ISymbol for my syntax node, I'm fail (getting null) when using SemanticModel.GetSymbolInfo but succeed when using SemanticModel.GetDeclaredSymbol.

I've attached an example bellow.

So my question is when to use each one of the methods for getting the semantic model?

public class Class1
{
    public System.String MyString { get; set; }

    public static void Main()
    {
        var str =
            @"
            namespace ClassLibrary31
            {
                public class Class1
                {
                    public System.String MyString { get; set; }
                }
            }";

        var syntaxTree = SyntaxFactory.ParseSyntaxTree(str);

        MetadataReference[] metadataReferenceReferences = new MetadataReference[]
        {
            MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
        };

        var compilation =
            CSharpCompilation
                .Create("TraceFluent",
                    new[] {syntaxTree},
                    options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, warningLevel:1),
                    references: metadataReferenceReferences
                );

        var temp = compilation.Emit("temp");
        var semanticModel = compilation.GetSemanticModel(syntaxTree, true);

        PropertyDeclarationSyntax propertySyntaxNode = 
            syntaxTree.GetRoot()
                .DescendantNodes()
                .OfType<PropertyDeclarationSyntax>()
                .First();



        //var qu = propertySyntaxNode.q

        //var symbolInfo = semanticModel.GetDeclaredSymbol(propertySyntaxNode);
        var symbol = semanticModel.GetDeclaredSymbol(propertySyntaxNode) as IPropertySymbol;
        var typeInfo = semanticModel.GetTypeInfo(propertySyntaxNode).Type;
    }
}

回答1:

I believe you mean getting the symbol for a given syntax node, and not getting the semantic model for the tree.

Generally, when you want to get the underlying symbol of a declaration (class, property, method, ...), then you should use the GetDeclaredSymbol. Internally, GetSymbolInfo calls this method. You can see the different cases handled there. Declarations are not handled, so for those you'd need to use GetDeclaredSymbol, whose internals you can find here.