我正在使用 Roslyn 库。我想在匹配行之后添加语句:这是要求。首先我想找到以下行:
_container.RegisterInstance(NavigationService);
然后我想在上面的行之后添加以下语句:
_container.RegisterInstance<ISessionStateService>(SessionStateService);
_container.RegisterInstance<IFlyoutService>(FlyoutService);
任何帮助将不胜感激。
编辑:(我已经创建了表达式,但现在如何将这两个表达式添加到我的 targetExpression?
string strContent = File.ReadAllText(strPath);
SyntaxTree tree = SyntaxTree.ParseText(strContent);
var targetExpression = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>()
.FirstOrDefault(
x => x.Expression.ToString().Contains("_container.RegisterInstance") && x.ArgumentList.ToString().Contains("NavigationService"));
InvocationExpressionSyntax replacementNode1 =
Syntax.InvocationExpression(Syntax.ParseExpression(@"_container.RegisterInstance<ISessionStateService>(SessionStateService);"));
InvocationExpressionSyntax replacementNode2 =
Syntax.InvocationExpression(Syntax.ParseExpression(@"_container.RegisterInstance<IFlyoutService>(FlyoutService);"));
MethodDeclarationSyntax targetMethod = (MethodDeclarationSyntax)targetExpression.Parent.Parent.Parent;
List<InvocationExpressionSyntax> list = targetMethod.DescendantNodes().OfType<InvocationExpressionSyntax>().ToList();
int index = list.IndexOf(targetExpression);
list.Insert(index + 1, replacementNode1);
list.Insert(index + 1, replacementNode2);
现在的问题是如何获取我更新的树?表示如何更新我的列表并通过这些更改获取树。
编辑:现在我可以生成添加节点,但唯一的问题是格式化..间距不正确。这是代码:
string strContent = File.ReadAllText(strPath);
SyntaxTree tree = SyntaxTree.ParseText(strContent);
ExpressionStatementSyntax expressionStatementSyntax =
Syntax.ExpressionStatement(Syntax.ParseExpression("_container.RegisterInstance(NavigationService);"));
var targetBlock =
tree.GetRoot()
.DescendantNodes()
.OfType<BlockSyntax>()
.FirstOrDefault(x => x.Statements.Any(y => y.ToString().Contains("_container.RegisterInstance")));
StatementSyntax syn1 =
Syntax.ParseStatement(@"_container.RegisterInstance<ISessionStateService>(SessionStateService);");
StatementSyntax syn2 = Syntax.ParseStatement(@"_container.RegisterInstance<ISessionStateService>(SessionStateService2);");
List<StatementSyntax> newSynList = new List<StatementSyntax> { syn1, syn2 };
SyntaxList<StatementSyntax> blockWithNewStatements = targetBlock.Statements;
foreach (var syn in newSynList)
{
blockWithNewStatements = blockWithNewStatements.Insert(1, syn);
}
BlockSyntax newBlock = Syntax.Block(blockWithNewStatements);
var newRoot = tree.GetRoot().ReplaceNode(targetBlock, newBlock);
它生成所有行左对齐的输出..有什么建议吗?