Roslyn CodeFixProvider为该方法添加属性

Ale*_*erM 4 c# roslyn

我正在为分析器构建CodeFixProvider,它正在检测方法声明中是否缺少自定义属性.基本上应该添加到方法的自定义属性看起来像

    [CustomAttribute(param1: false, param2: new int[]{1,2,3})]
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所得到的:

    public sealed override async Task RegisterCodeFixesAsync( CodeFixContext context ) {
        var root = await context.Document.GetSyntaxRootAsync( context.CancellationToken ).ConfigureAwait( false );

        var diagnostic = context.Diagnostics.First();
        var diagnosticSpan = diagnostic.Location.SourceSpan;
        var declaration = root.FindToken( diagnosticSpan.Start ).Parent.AncestorsAndSelf( ).OfType<MethodDeclarationSyntax>( ).First( );

        context.RegisterCodeFix(
            CodeAction.Create(
                title: title,
                createChangedSolution: c => this.AddCustomAttribute(context.Document, declaration, c),
                equivalenceKey: title),
            diagnostic);
    }

    private async Task<Solution> AddCustomAttribute( Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken ) {
        // I suspect I need to do something like methodDeclaration.AddAttributeLists(new AttributeListSyntax[] {
        // but not sure how to use it exactly

        throw new NotImplementedException( );
    }
Run Code Online (Sandbox Code Playgroud)

m0s*_*0sa 14

请记住,roslyn语法树是不可变的.你需要这样的东西:

private async Task<Solution> AddCustomAttribute(Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken)
{
    var root = await document.GetSyntaxRootAsync(cancellationToken);
    var attributes = methodDeclaration.AttributeLists.Add(
        SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
            SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("CustomAttribute"))
            //  .WithArgumentList(...)
        )).NormalizeWhitespace());

    return document.WithSyntaxRoot(
        root.ReplaceNode(
            methodDeclaration,
            methodDeclaration.WithAttributeLists(attributes)
        )).Project.Solution;
}
Run Code Online (Sandbox Code Playgroud)

要获取SyntaxFactory属性构造函数的完整代码,请将.WithArgumentList()其抛入Roslyn Quoter.