How to create AttributeSyntax with parameter

I am trying to use Roslyn to create a parameter that looks something like this:

[MyAttribute("some_param")]

Now I can easily create an AttributeSyntax , but I cannot figure out how to add an argument to an ArgumentList porperty using the .AddArguments(ExpressionSyntax) method. I'm just not sure what I need to do to create the appropriate expression.

+5
source share
1 answer

I am a fan of SyntaxFactory.Parse* methods. (They are usually easier to understand)

To generate an attribute, you can use the following:

 var name = SyntaxFactory.ParseName("MyAttribute"); var arguments = SyntaxFactory.ParseAttributeArgumentList("(\"some_param\")"); var attribute = SyntaxFactory.Attribute(name, arguments); //MyAttribute("some_param") var attributeList = new SeparatedSyntaxList<AttributeSyntax>(); attributeList = attributeList.Add(attribute); var list = SyntaxFactory.AttributeList(attributeList); //[MyAttribute("some_param")] 

Alternatively, you can use the hand tool from the Kirill RoslynQuoter tool. But I think that the fact that no one wants to write this code without its tool says ...;)

The manual approach looks like this:

 var attributeArgument = SyntaxFactory.AttributeArgument( SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Token(default(SyntaxTriviaList), SyntaxKind.StringLiteralToken, "some_param", "some_param", default(SyntaxTriviaList)))); var otherList = new SeparatedSyntaxList<AttributeArgumentSyntax>(); otherList = otherList.Add(attributeArgument); var argumentList = SyntaxFactory.AttributeArgumentList(otherList); var attribute2 = SyntaxFactory.Attribute(name, argumentList); 

In your example, you want to add StringLiteralExpression as an argument.

+5
source

Source: https://habr.com/ru/post/1244849/


All Articles