【问题标题】:Roslyn Analyzer to replace type declarationsRoslyn Analyzer 替换类型声明
【发布时间】:2020-07-02 05:57:29
【问题描述】:

我需要实现 Roslyn Analyzer 和 CodeFixProvider 来替换属性和参数中声明的类型。 例如,我有一个像

这样的声明
public IReadOnlyCollection<string> Collection { get; }

我需要将其替换为

public IReadOnlyList<string> Collection { get; }

问题:使用 DiagnosticAnalyzer 的后代类在源中查找此类位置的最佳方法是什么? 有很多方法,例如:

RegisterSyntaxNodeAction()
RegisterSymbolAction()
RegisterSyntaxTreeAction()

从哪里开始会更好?如果可能的话,最好也能找到一些例子。

【问题讨论】:

    标签: c# visual-studio roslyn-code-analysis


    【解决方案1】:

    最后,我设法以这种方式实现它:

    public override void Initialize(AnalysisContext context)
    {
        context.EnableConcurrentExecution();
        context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
    
        context.RegisterSyntaxNodeAction(
            AnalyzeNode,
            SyntaxKind.PropertyDeclaration,
            SyntaxKind.FieldDeclaration,
            SyntaxKind.Parameter);
    }
    
    private void AnalyzeNode(SyntaxNodeAnalysisContext context)
    {
        var type = context.Node switch
        {
            PropertyDeclarationSyntax p => p.Type,
            FieldDeclarationSyntax p => p.Declaration.Type,
            ParameterSyntax p => p.Type,
            _ => null
        };
    
        if (type is null)
            return;
    
        if (!(type is GenericNameSyntax))
            return;
    
        if (type.GetFirstToken().ToString() == "IReadOnlyCollection")
        {
            var diagnostic = Diagnostic.Create(Rule, type.GetLocation());
            context.ReportDiagnostic(diagnostic);
        }
    }
    
    

    在我看来看起来不错。如果您知道更好的方法,请随时添加更多详细信息。

    【讨论】:

    • 是否应该处理另一个对象(数组、列表字典等)中的 IReadOnlyCollection 的情况? IE。 arr[] IReadOnlyCollection
    • @jmoreno 此实现仅适用于属性、字段和参数声明中的 IReadOnlyCollection。它不适用于 IList> 之类的东西
    猜你喜欢
    • 1970-01-01
    • 2019-07-24
    • 2019-01-07
    • 1970-01-01
    • 2012-10-24
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    • 1970-01-01
    相关资源
    最近更新 更多