其他分享
首页 > 其他分享> > CodeGo.net>如何确定FieldDeclarationSyntax的类型是否是罗斯林的接口?

CodeGo.net>如何确定FieldDeclarationSyntax的类型是否是罗斯林的接口?

作者:互联网

假设有一个包含接口类型的私有字段的类.
当使用Roslyn分析上面的代码时,如何确定FieldDeclarationSyntax背后的类型是否是接口?使用下面的代码检索字段声明的ISymbol,我找不到任何属性,例如IsInterface或类似属性.

using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

public class SampleClass
{
    public static void Main()
    {
        var str =
            @"
            namespace Sample
            {
                public interface IBar
                {
                    void Do();
                }

                public class Foo
                {
                    private IBar _bar;
                }
            }";

        var syntaxTree = SyntaxFactory.ParseSyntaxTree(str);

        var compilation = CSharpCompilation.Create("Sample", new[] { syntaxTree });

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

        var classDeclarationSyntax =
        semanticModel.SyntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().First();

        var fieldDeclarationSyntax = classDeclarationSyntax.DescendantNodes().OfType<FieldDeclarationSyntax>().First();

        var declaredSymbol = semanticModel.GetDeclaredSymbol(fieldDeclarationSyntax.Declaration.Variables.First());

        // declaredSymbol (ISymbol) contains properties like IsDefinition, IsVirtual etc. but nothing like IsInterface.
    }
}

解决方法:

最终,在fieldDeclarationSyntax.Declaration.Type上调用GetTypeInfo达到了目的.
完整的工作示例:

using System;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;

public class SanpleClass
{
    public static void Main()
    {
        var str =
            @"
            namespace Sample
            {
                public interface IBar
                {
                    void Do();
                }

                public class Foo
                {
                    private IBar _bar;
                }
            }";

        var syntaxTree = SyntaxFactory.ParseSyntaxTree(str);

        var compilation = CSharpCompilation.Create("Sample", new[] { syntaxTree });

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

        var classDeclarationSyntax =
            semanticModel.SyntaxTree.GetRoot().DescendantNodes().OfType<ClassDeclarationSyntax>().First();

        var fieldDeclarationSyntax = classDeclarationSyntax.DescendantNodes().OfType<FieldDeclarationSyntax>().First();

        var typeKind = semanticModel.GetTypeInfo(fieldDeclarationSyntax.Declaration.Type).Type.TypeKind;

        var isInterface = typeKind == TypeKind.Interface;

        Console.WriteLine($"Is Interface: {isInterface}");
    }
}

标签:roslyn,roslyn-code-analysis,c
来源: https://codeday.me/bug/20191211/2105791.html