如何获取用某个属性注释的所有属性? [英] How to get all properties that are anotated with some attribute?

查看:47
本文介绍了如何获取用某个属性注释的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始使用 Roslyn,我想找到所有用属性名称OneToOne"注释的属性.我启动了 SyntaxVisualizer 并能够获得对该节点的引用,但我想知道是否有更简单的方法来实现这一点.这就是我所拥有的:

I am just starting with Roslyn, and I want to find all properties that are annotated with attribute names "OneToOne". I fired up SyntaxVisualizer and was able to get reference to that node, but I am wondering is there a simpler way to achieve this. This is what I have:

var prop = document.GetSyntaxRoot()
             .DescendantNodes()
             .OfType<PropertyDeclarationSyntax>()
             .Where(p => p.DescendantNodes()
                 .OfType<AttributeSyntax>()
                 .Any(a => a.DescendantNodes()
                     .OfType<IdentifierNameSyntax>()
                     .Any(i => i.DescendantTokens()
                         .Any(dt => dt.Kind == SyntaxKind.IdentifierToken
                                 && dt.ValueText == "OneToOne"))))

推荐答案

好吧,我会使用语义而不是语法来解决这个问题.像(从我的头顶):

Well, I would go about this using Semantics, not Syntax. Something like (off the top of my head):

var attributeSymbol = compilation.GetTypeByMetadataName("ConsoleApplication1.OneToOneAttribute");
var propertySymbol = compilation.GetTypeByMetadataName("ConsoleApplication1.Program")
                     .GetMembers()
                     .Where(m => 
                            m.Kind == CommonSymbolKind.Property && 
                            m.GetAttributes().Any(a => a.AttributeClass.MetadataName == attributeSymbol.MetadataName));

这篇关于如何获取用某个属性注释的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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