如何检索所有(且仅)class 个变量?
How do I retrieve all (and only) class variables?
我需要提取所有 class 变量。但是我的代码 returns 所有变量,包括在方法(局部变量)中声明的变量。例如:
class MyClass
{
private int x;
private int y;
public void MyMethod()
{
int z = 0;
}
}
我只需要 x
和 y
,但我得到了 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();
});
});
您应该过滤 FieldDeclarationSyntax
,显然,它仅指字段(也称为 class 变量)。
虽然我不确定你为什么要经历额外的 MemberDeclarationSyntax
圈:cls.DescendantNodes().OfType<FieldDeclarationSyntax>()
应该工作得很好,因为你仍然要遍历树。
之后,FieldDeclarationSyntax.Declaration
保存您感兴趣的内容:VariableDeclarationSyntax
。
我需要提取所有 class 变量。但是我的代码 returns 所有变量,包括在方法(局部变量)中声明的变量。例如:
class MyClass
{
private int x;
private int y;
public void MyMethod()
{
int z = 0;
}
}
我只需要 x
和 y
,但我得到了 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();
});
});
您应该过滤 FieldDeclarationSyntax
,显然,它仅指字段(也称为 class 变量)。
虽然我不确定你为什么要经历额外的 MemberDeclarationSyntax
圈:cls.DescendantNodes().OfType<FieldDeclarationSyntax>()
应该工作得很好,因为你仍然要遍历树。
之后,FieldDeclarationSyntax.Declaration
保存您感兴趣的内容:VariableDeclarationSyntax
。