我最后开始探索Roslyn,现在我想编写一个CodeRefactoringProvider
来创建一个新文件,而不是替换当前的代码。我当前的代码简单地重命名了这样一个类:
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = nameof(TransportModelCodeRefactoringProvider)), Shared]
internal class TransportModelCodeRefactoringProvider : CodeRefactoringProvider
{
private const string Title = "Make TransportModel class";
public override sealed async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var node = root.FindNode(context.Span);
var classDeclaration = node as ClassDeclarationSyntax;
if (classDeclaration == null)
{
// current node is not a class declaration
return;
}
var action = CodeAction.Create(Title, token => MakeTransportModelAsync(context.Document, classDeclaration, token), Title);
context.RegisterRefactoring(action);
}
private async Task<Document> MakeTransportModelAsync(Document document, ClassDeclarationSyntax classDeclaration, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
var newRoot = (CompilationUnitSyntax)root;
var newName = classDeclaration.Identifier + "TransportModel";
var newId = SyntaxFactory.Identifier(classDeclaration.Identifier.LeadingTrivia, SyntaxKind.IdentifierToken, newName, newName, classDeclaration.Identifier.TrailingTrivia);
var newClass = classDeclaration.ReplaceToken(classDeclaration.Identifier, newId);
newRoot = newRoot.ReplaceNode(classDeclaration, newClass).NormalizeWhitespace();
var result = document.WithSyntaxRoot(newRoot);
return result;
}
}
我发现CodeAction.Create
的过载接受Task<Solution>
,我觉得这很有趣,但后来我不知道如何获得当前文档的解决方案和/或项目。
答案 0 :(得分:3)
拨打CodeAction.Create
的{{3}},其中有一位代表返回Solution
。
然后,您可以根据Solution
返回context.Document.Project.Solution
,并添加新文档。