2016-08-31 31 views
2

我正在用Roslyn做一个分析器,将postsharp [NotNull]属性添加到方法参数中。使用Roslyn codefix向方法参数添加一个属性

private async Task<Document> MakeNotNullAsync(Document document, MethodDeclarationSyntax method, CancellationToken cancellationToken, string paramName) 
    { 

     var parameters = method.ChildNodes().OfType<ParameterListSyntax>().First(); 
     var param = parameters.ChildNodes().OfType<ParameterSyntax>().First() as SyntaxNode; 



     NameSyntax name = SyntaxFactory.ParseName("NotNull"); 
     AttributeSyntax attribute = SyntaxFactory.Attribute(name, null); 
     Collection<AttributeSyntax> list = new Collection<AttributeSyntax>(); 
     list.Add(attribute); 
     var separatedlist = SyntaxFactory.SeparatedList(list); 
     var newLiteral = SyntaxFactory.AttributeList(separatedlist); 
     Collection<SyntaxNode> synlist = new Collection<SyntaxNode>(); 
     synlist.Add(newLiteral); 

     var root = await document.GetSyntaxRootAsync(); 
     var newRoot = root.InsertNodesBefore(param, synlist); 
     var newDocument = document.WithSyntaxRoot(newRoot); 
     return newDocument; 

这里是我到目前为止(肯定还有一个更简单的方法来做到这一点),但我得到一个则“”时,它试图做root.InsertNodesBefore()。有一个更好的方法吗?

+0

什么是消息和堆栈跟踪? – SLaks

回答

0

我通常发现使用ReplaceNode更容易。在你的情况,你就必须有一个具有新特性(通过WithAttributeLists)取代param

var attribute = SyntaxFactory.AttributeList(
    SyntaxFactory.SingletonSeparatedList<AttributeSyntax>(
     SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("NotNull"), null))); 
var newParam = param.WithAttributeLists(param.AttributeLists.Add(attribute)); 

var root = await document.GetSyntaxRootAsync(); 
var newRoot = root.ReplaceNode(param, newParam);  
var newDocument = document.WithSyntaxRoot(newRoot); 
return newDocument; 

注意,这也处理,其中param已经现有属性的情况下。

相关问题