假设有一个包含接口类型的私有字段的类。
使用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.
}
}
答案 0 :(得分:2)
在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}");
}
}