【问题标题】:How can I detect missing attributes on a method with Roslyn Code analyser如何使用 Roslyn 代码分析器检测方法中缺失的属性
【发布时间】:2022-11-11 04:13:21
【问题描述】:

我正在关注本教程,https://learn.microsoft.com/en-us/dotnet/csharp/roslyn-sdk/tutorials/how-to-write-csharp-analyzer-code-fix

我真正想要的是检测 ASP.Net Web API 控制器中的方法是否缺少我的 Custom 属性,并提示开发人员添加它。

在我的 Analyzer 的 Initilize 方法中,我选择了 MethodDeclaration 作为 SyntaxKind 像这样

context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.MethodDeclaration);

在 AnalyzeNode 方法中,我想检测有问题的方法是否已经添加了 Custom 属性。

    private void AnalyzeNode(SyntaxNodeAnalysisContext context)
    {
        var methodDeclaration = (MethodDeclarationSyntax)context.Node;

        // make sure the declaration isn't already const:
        if (methodDeclaration.AttributeLists.Any(x=> x. ))
        {
            return;
        }

不确定在这段代码中需要做什么来查找是否已应用 Custom 属性。

最终我希望我的代码分析器让用户添加缺少的属性

    [Route("/routex")]
    [Custom()]
    public async Task<IHttpActionResult> AlreadyHasCustomAttribute()
    {
        //everything is good, no hint shown to the user
    }

    [Route("/routey")]
    public async Task<IHttpActionResult> DoesNotHaveCustomAttribute()
    {
        //missing Custom attribute, show hint to the user and add the attribute as a code fix
    }

请提出解决方案。谢谢。

【问题讨论】:

    标签: c# roslyn roslyn-code-analysis


    【解决方案1】:

    出于性能原因,最简单的方法可能是简单地调用methodDeclaration.AttributeLists.Any()) 只是为了在继续之前验证它是否具有属性。完成后,您可以调用 context.SemanticModel.GetDeclaredSymbol(methodDeclaration),这将为您提供一个 IMethodSymbol,您可以在其上调用 GetAttributes()。从那里,您可以遍历属性列表并找到您正在寻找的那个(或者在这种情况下,找到它的缺失。)

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      • 2020-11-11
      • 2012-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多