简体   繁体   English

如何使用参数创建AttributeSyntax

[英]How to create an AttributeSyntax with a parameter

I'm trying to use Roslyn to create a parameter that looks something like this: 我正在尝试使用Roslyn创建一个看起来像这样的参数:

[MyAttribute("some_param")]

Now I can easily create the AttributeSyntax but can't figure out how to add an argument to the ArgumentList porperty using the .AddArguments(ExpressionSyntax) method. 现在我可以轻松创建AttributeSyntax但无法弄清楚如何使用.AddArguments(ExpressionSyntax)方法向ArgumentList AttributeSyntax添加参数。 I'm just not sure what I need to do to create the appropriate expression. 我只是不确定我需要做什么才能创建合适的表达式。

I'm a fan of the SyntaxFactory.Parse* methods. 我是SyntaxFactory.Parse*方法的粉丝。 (They're usually easier to understand) (他们通常更容易理解)

You could use the following to generate the attribute you're looking for: 您可以使用以下命令生成您正在寻找的属性:

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 could use hand-crafted approach from Kirill's RoslynQuoter tool. 或者,您可以使用Kirill的RoslynQuoter工具手工制作的方法。 But I think the fact that no one wants to write that code without his tool is telling... ;) 但我认为没有人想要在没有他的工具的情况下编写代码的事实就是在说; ...)

The manual approach looks like: 手动方法如下:

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 a StringLiteralExpression as your argument. 在您的示例中,您希望添加StringLiteralExpression作为参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM