我使用Roslyn在各种项目中重写几个方法,并在某些情况下注入方法参数。这样可以创建类似于以下内容的输出:
GetFilter(Data.Application.Interfaces.IDataSession session, string name)
我想要它做的是在类中添加一个Using Directive并将参数添加为:
GetFilter(IDataSession session, string name)
我看过几个例子,但我遗漏了一些东西。当我添加以下代码来更新Using时,它会停止做任何事情。
public class DbBaseReferencesMethodRewriter : CSharpSyntaxRewriter
{
public override SyntaxNode VisitMethodDeclaration(MethodDeclarationSyntax node)
{
if (RewriterUtility.HasDriveSessionParameter(node)) return node;
// Start: Add to Using Directives
var qualifiedName = SyntaxFactory.ParseName("Data.Application.Interfaces");
var usingDirective = SyntaxFactory.UsingDirective(qualifiedName);
var rootNode = node.SyntaxTree.GetRoot() as CompilationUnitSyntax;
rootNode = rootNode.AddUsings(usingDirective).NormalizeWhitespace();
// End: Add to Using Directives
return CreatesDbBaseWithParameterlessConstructor(node)
? node.PrependParameter(RewriterUtility.CreateDriveSessionParameter())
: node;
}
private static bool CreatesDbBaseWithParameterlessConstructor(SyntaxNode node)
{
return node.DescendantNodes()
.OfType<ObjectCreationExpressionSyntax>()
.Any(RewriterUtility.HasParameterlessDbBaseCall);
}
}
答案 0 :(得分:1)
private (SyntaxTree, SyntaxTree) UpdateUsingDirectivesForChanges((SyntaxTree, SyntaxTree) change)
{
var qualifiedName = SyntaxFactory.ParseName(" Data.Application.Interfaces");
var usingDirective = SyntaxFactory.UsingDirective(qualifiedName);
var rootNode = change.Item2.GetRoot() as CompilationUnitSyntax;
if (!rootNode.Usings.Select(d => d.Name.ToString()).Any(u => u == qualifiedName.ToString()))
{
rootNode = rootNode.AddUsings(usingDirective);
change.Item2 = rootNode.SyntaxTree;
}
return change;
}