What is the canonical way to convert a MethodDeclarationSyntax to a ConstructorDeclarationSyntax?

为君一笑 提交于 2019-12-25 04:23:00

问题


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

from:

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

to

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.

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.


回答1:


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.

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



来源:https://stackoverflow.com/questions/40578806/what-is-the-canonical-way-to-convert-a-methoddeclarationsyntax-to-a-constructord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!