[英]Roslyn syntax tree transformation - Replacing return type of methods
I am trying to write code transformation using Roslyn that changes return type of interface methods from T
to Task<T>
(assuming no void returns). 我正在尝试使用Roslyn编写代码转换,该转换将接口方法的返回类型从T
更改为Task<T>
(假设没有void返回)。 Following is the code I came up with. 以下是我想出的代码。
CODE 码
InterfaceDeclarationSyntax asyncInterface = syncInterface.ReplaceNodes(
syncInterface.Members.OfType<MethodDeclarationSyntax>(),
(a, m) => m.ReplaceNode(
m.ReturnType,
SF.GenericName(SF.Identifier("Task"), SF.TypeArgumentList(new SeparatedSyntaxList<TypeSyntax>().Add(m.ReturnType)))));
Firstly is this the right approach? 首先 ,这是正确的方法吗?
Secondly this messes up the indentation when formatted. 其次 ,格式化时会弄乱缩进。 How should I fix that? 我该如何解决?
Edit 编辑
I was able to solve second problem by preserving Trivia. 通过保留Trivia,我能够解决第二个问题。 Here is the updated code (I also migrated it to use rewriter). 这是更新的代码(我也将其迁移为使用重写器)。
Code 码
sealed class AsyncMethodRewriter : CSharpSyntaxRewriter
{
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax m)
{
var newReturnType = SF.GenericName(SF.Identifier("Task"), SF.TypeArgumentList(new SeparatedSyntaxList<TypeSyntax>().Add(m.ReturnType.WithoutTrivia())));
newReturnType = newReturnType.InsertTriviaBefore(newReturnType.GetLeadingTrivia().First(), m.ReturnType.GetLeadingTrivia().AsEnumerable());
newReturnType = newReturnType.InsertTriviaAfter(newReturnType.GetTrailingTrivia().First(), m.ReturnType.GetTrailingTrivia().AsEnumerable());
return m.ReplaceNode(m.ReturnType, newReturnType);
}
}
WithReturnType
method for MethodDeclarationSyntax
and AddTypeArgumentListArguments
method for GenericNameSyntax
class 你选择正确的方法,但你可以简化代码WithReturnType
的方法MethodDeclarationSyntax
和AddTypeArgumentListArguments
方法GenericNameSyntax
类 NormalizeWhitespace()
method for format leading and trailing trivias 尝试将NormalizeWhitespace()
方法用于格式前导和尾随琐事 try this code: 试试这个代码:
syncInterface
.ReplaceNodes(
syncInterface.Members.OfType<MethodDeclarationSyntax>(),
(a, b) =>
b.WithReturnType(
SyntaxFactory.GenericName("Task").AddTypeArgumentListArguments(b.ReturnType)))
.NormalizeWhitespace();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.