如何检索所有(且仅)类变量?

blu*_*ray 5 c# roslyn

我需要提取所有类变量。但是我的代码返回所有变量,包括在方法(本地)中声明的变量。例如:

class MyClass
{
    private int x;
    private int y;

    public void MyMethod()
    {
        int z = 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

我只需要得到xandy但我得到x, y, 和z。到目前为止我的代码:

SyntaxTree tree = CSharpSyntaxTree.ParseText(content);
IEnumerable<SyntaxNode> nodes = ((CompilationUnitSyntax) tree.GetRoot()).DescendantNodes();

List<ClassDeclarationSyntax> classDeclarationList = nodes
    .OfType<ClassDeclarationSyntax>().ToList();

classDeclarationList.ForEach(cls =>
{
    List<MemberDeclarationSyntax> memberDeclarationSyntax = cls.Members.ToList();
    memberDeclarationSyntax.ForEach(x =>
    {
        //contains all variables
        List<VariableDeclarationSyntax> variables = x.DescendantNodes()
           .OfType<VariableDeclarationSyntax>().ToList();
    });
});
Run Code Online (Sandbox Code Playgroud)

Jer*_*vel 5

您应该过滤FieldDeclarationSyntax哪些显然只引用字段(也称为类变量)。

我不确定你为什么要经历额外的环MemberDeclarationSyntaxcls.DescendantNodes().OfType<FieldDeclarationSyntax>()应该工作得很好,因为无论如何你仍然要遍历树。

之后,FieldDeclarationSyntax.Declaration保存您感兴趣的内容:VariableDeclarationSyntax.