如何在 Roslyn 中查找具有特定名称的字段类型 [英] How to find type of the field with specific name in Roslyn

查看:31
本文介绍了如何在 Roslyn 中查找具有特定名称的字段类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要使用 Roslyn 查找TypeSyntax 或本质上Type 类中的特定文件.
像这样:

Need to find TypeSyntax or essentially Type of a specific filed in class by using Roslyn.
Something like this:

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

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

But could not get any hint about how to reach Identifier and SyntaxType in FieldDeclarationSyntax node. Any idea please?

推荐答案

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

Part of the issue is that fields can contain multiple variables. You'll look at Declaration for type and Variables for identifiers. I think this is what you're looking for:

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();

这篇关于如何在 Roslyn 中查找具有特定名称的字段类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆