简体   繁体   English

Roslyn CodeFixProvider为该方法添加属性

[英]Roslyn CodeFixProvider add attribute to the method

I'm building CodeFixProvider for the analyzer that is detecting if custom attribute is missing from the method declaration. 我正在为分析器构建CodeFixProvider,它正在检测方法声明中是否缺少自定义属性。 Basically custom attribute that should be added to the method looks like 基本上应该添加到方法的自定义属性看起来像

    [CustomAttribute(param1: false, param2: new int[]{1,2,3})]

this is what I've got so far: 这是我到目前为止所得到的:

    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( );
    }

Remember, roslyn syntax trees are immutable. 请记住,roslyn语法树是不可变的。 You'll need something like: 你需要这样的东西:

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;
}

To get the full SyntaxFactory code for the attribute constructor .WithArgumentList() throw it into the Roslyn Quoter . 要获取属性构造函数.WithArgumentList()的完整SyntaxFactory代码,请将其抛入Roslyn Quoter

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM