2016-08-31 7 views
2

私はメソッドのパラメータにpostsharp [NotNull]属性を追加するためにRoslynでアナライザーを作成しています。ここでRoslynコードフィックスでメソッドパラメータに属性を追加する

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を行おうと「System.InvalidCastExceptionの」を取得しています。これを行うより良い方法はありますか?

+0

メッセージとスタックトレースとはなんですか? – SLaks

答えて

0

私は通常、ReplaceNodeで作業するほうがずっと簡単です。これはまた、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; 

注:あなたのケースでは、あなただけ(WithAttributeListsを経由して)新しい属性を持っているものとparamを交換する必要があります。

関連する問題