将 MethodDeclarationSyntax 转换为 ConstructorDeclarationSyntax 的规范方法是什么? [英] What is the canonical way to convert a MethodDeclarationSyntax to a ConstructorDeclarationSyntax?

查看:56
本文介绍了将 MethodDeclarationSyntax 转换为 ConstructorDeclarationSyntax 的规范方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 API 迁移编写分析器和代码修复程序 (AutoMapper V5 Profiles),将protected override Configure 方法转换为构造函数:

I'm writing an analyzer and codefix for an API migration (AutoMapper V5 Profiles), converting a protected override Configure method to a constructor:

来自:

public class MappingProfile : Profile
{
    protected override Configure()
    {
        CreateMap<Foo, Bar>();
        RecognizePrefix("m_");
    }
}

public class MappingProfile : Profile
{
    public MappingProfile()
    {
        CreateMap<Foo, Bar>();
        RecognizePrefix("m_");
    }
}

我找到了一种将方法节点转换为构造函数的方法,但我一直在努力使空格正确.如果我没有忽略将方法转换为构造函数的更简单方法,这就引出了一个问题.

I've found a way to convert the method node into a constructor, but I've been struggling a lot to get the whitespace right. This begs the question if I'm not overlooking a simpler way of converting a method to constructor.

所以我的问题是:Roslyn 是否已经为您提供了将 MethodDeclarationSyntax 转换为 ConstructorDeclarationSyntax 的重构?或者比 这个 LINQPad 脚本更简单的方法.

So my question is: does Roslyn already give you a refactoring to convert a MethodDeclarationSyntax to a ConstructorDeclarationSyntax? Or an easier way than this LINQPad script.

推荐答案

在 CodeFix 中,只需添加 formatter annotation:

In a CodeFix, just add the formatter annotation:

SyntaxFactory
    .ConstructorDeclaration(constructorIdentifier)
    .‌​WithModifiers(Syntax‌​Factory.TokenList(Sy‌​ntaxFactory.Token(Sy‌​ntaxKind.PublicKeywo‌​rd)))
    .WithAttributeL‌​ists(oldMethodNode.A‌​ttributeLists)
    .WithP‌​arameterList(newPara‌​meterList)
    .WithBody(‌​newBody)
    .WithTriviaF‌​rom(oldMethodNode)
    .W‌​ithAdditionalAnnotat‌​ions(Formatter.Annot‌​ation)

这足以解决代码修复问题,因为代码修复基础架构将处理注释.

That's enough to do the trick in a code fix, because the code fix infrastructure will process the annotation.

在 CodeFix 之外,您可以使用 Microsoft.CodeAnalysis.Formatting 中的 Formatter.Format() 来显式处理注释.

Outside of a CodeFix, you can use Formatter.Format() from Microsoft.CodeAnalysis.Formatting to process the annotation explicitely.

这篇关于将 MethodDeclarationSyntax 转换为 ConstructorDeclarationSyntax 的规范方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆