我正在使用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);
它生成输出,所有行都保持对齐..任何建议?
答案 0 :(得分:7)
在编辑之后,看起来剩下的主要问题是关于处理行格式。在这两种情况下,一旦你获得了最终的根,你可以调用一个格式化程序来清理它。您有两种选择: