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

馋奶兔 提交于 2020-01-02 07:27:30

问题


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

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


回答1:


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


来源:https://stackoverflow.com/questions/33420559/how-to-find-type-of-the-field-with-specific-name-in-roslyn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!