问题
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(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
.WithAttributeLists(oldMethodNode.AttributeLists)
.WithParameterList(newParameterList)
.WithBody(newBody)
.WithTriviaFrom(oldMethodNode)
.WithAdditionalAnnotations(Formatter.Annotation)
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