假设有一个包含接口类型私有字段的类。使用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.
}
}