如何在 Roslyn 中查找具有特定名称的字段类型

How to find type of the field with specific name in Roslyn

需要使用 Roslyn 在 class 中找到特定文件的 TypeSyntax 或本质上 Type
像这样:

rootSyntaxNode
.DescendantNodes()
.OfType<FieldDeclarationSyntax>()
.First(x => x.Identifier="fieldName")
.GivemeTypeSyntax()

但无法获得有关如何在 FieldDeclarationSyntax 节点中获取 Identifier 和 SyntaxType 的任何提示。有什么想法吗?

部分问题是字段可以包含多个变量。您将查看 Declaration 类型和 Variables 标识符。我想这就是您要找的:

var tree = CSharpSyntaxTree.ParseText(@"
class MyClass
{
    int firstVariable, secondVariable;
    string thirdVariable;
}");

var mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location);
var compilation = CSharpCompilation.Create("MyCompilation",
    syntaxTrees: new[] { tree }, references: new[] { mscorlib });

var fields = tree.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>();

//Get a particular variable in a field
var second = fields.SelectMany(n => n.Declaration.Variables).Where(n => n.Identifier.ValueText == "secondVariable").Single();
//Get the type of both of the first two fields.
var type = fields.First().Declaration.Type;
//Get the third variable
var third = fields.SelectMany(n => n.Declaration.Variables).Where(n => n.Identifier.ValueText == "thirdVariable").Single();