c# - Roslyn CodeFixProvider 向方法添加属性

标签 c# roslyn

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

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

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

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

最佳答案

请记住,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;
}

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

关于c# - Roslyn CodeFixProvider 向方法添加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37594739/

相关文章:

c# - 如何使用 EF.Functions 评估 Func<T, bool>?

c# - 我找不到内联表达式变量的代码

c# - 有没有办法以编程方式将类从一个 namespace 移动到另一个 namespace ?

c# - 数据注释和 MVC 1 :1 ViewModel

c# - 异步调用新手问题

c# - 向 IEnumerable<T> 添加一项的最佳方法是什么?

c# - 获取在另一个程序集/项目中声明的类型的类型信息

c# - 如何使用 Microsoft.Azure.Storage.Blob 从 url 读取 blob?

c# - 动态添加数据后 CheckBoxList ListItem Count 始终为 0

c# - 为 Roslyn SyntaxFactory 指定语言版本