加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 查找基本类型的属性

发布时间:2020-12-15 21:51:21 所属栏目:百科 来源:网络整理
导读:我正在尝试实现ICodeIssueProvider来检测类(或其基类型之一)是否具有某个属性. public IEnumerableCodeIssue GetIssues(IDocument document,CommonSyntaxNode node,CancellationToken cancellationToken) { var methodDeclaration = (MethodDeclarationSynta
我正在尝试实现ICodeIssueProvider来检测类(或其基类型之一)是否具有某个属性.

public IEnumerable<CodeIssue> GetIssues(IDocument document,CommonSyntaxNode node,CancellationToken cancellationToken)
    {
        var methodDeclaration = (MethodDeclarationSyntax)node;
        var semanticModel = document.GetSemanticModel(cancellationToken);

        var methodSymbol = semanticModel.GetDeclaredSymbol(methodDeclaration);
        var typeSymbol = methodSymbol.ContainingType;

        // The following only gets attributes declared on this class,how to
        // also include those declared on a base class ?
        var attributes = typeSymbol.GetAttributes();

有没有一种更好的方法比走上typeSymbol.BaseType一直到System.Object并在途中调用GetAttributes()?

另外,有没有更好的方法来检查typeSymbol是否派生自特定的类而不是向上走.BaseType并手动检查

(是的,有一个原因从下面的示例中看不到检查MethodDeclarationSyntax节点而不是ClassDeclarationSyntax节点)

解决方法

tldr;不,没有单一的方法调用(截至2012年9月CTP Roslyn).

您需要搜索的父类可能(通常是)与您所在的类完全独立的语法树.如果您的所有类都在单个名称空间声明(颤抖)中,那么您可以从该SyntaxNode根进行搜索.

有可能,你的类是每个文件一个,所以虽然它们共享相同的命名空间,但它们不在同一个语法树根目录下.

Roslyn引起了很大的麻烦,因为语法树更类似于代码文件的布局而不是代码所代表的类型.

可能有一种方法可以在该namsepace下存在的所有类中创建新的语法树(现有的语法树是不可变的),然后搜索该树.对我而言,这种感觉就像复杂而不是需要,特别是作为一种助产父母的方法更易于维护.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读