【问题标题】:How to find type of the field with specific name in Roslyn如何在 Roslyn 中查找具有特定名称的字段类型
【发布时间】:2015-10-29 17:10:38
【问题描述】:

需要使用 Roslyn 查找类中特定字段的 TypeSyntax 或基本上是 Type
像这样的:

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

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

【问题讨论】:

    标签: c# roslyn roslyn-code-analysis


    【解决方案1】:

    部分问题在于字段可以包含多个变量。您将查看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();
    

    【讨论】:

    • 也许我对什么是“字段”感到困惑,但那不是 3 个字段和 3 个变量吗?意思是不是int first, second; 只是int first; int second; 的简写同义词,还是我错过了什么?
    猜你喜欢
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-12
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多