简体   繁体   English

如何使用 Roslyn 声明 var 变量?

[英]How do I declare a var variable with Roslyn?

I've got the following piece of code, but I can't find how to get the var TypeSyntax .我有以下代码,但我找不到如何获取 var TypeSyntax Any ideas?有任何想法吗?

Syntax.LocalDeclarationStatement(                   
    declaration: Syntax.VariableDeclaration(
        type: Syntax.PredefinedType(Syntax.Token(SyntaxKind.VarKeyword)),
        variables: Syntax.SeparatedList(
        Syntax.VariableDeclarator(
            identifier: Syntax.Identifier(name)))
        )
    )
);

this fails with an Argument exception that says: "keyword"这会失败,并出现一个参数异常,上面写着:“关键字”

I'd use:我会使用:

Syntax.LocalDeclarationStatement(
    declaration: Syntax.VariableDeclaration(
        type: Syntax.IdentifierName(Syntax.Token(SyntaxKind.VarKeyword)),
        variables: Syntax.SeparatedList(new[] { 
            Syntax.VariableDeclarator(
                identifier: Syntax.Identifier(name)) })));

Jb Evain's answer is correct; Jb Evain 的回答是正确的; I just thought that I would add that the reason for the error is because "var" is not a predefined type .我只是想我会补充一点,错误的原因是因为“var”不是预定义的类型 A predefined type is something like "int" or "string".预定义类型类似于“int”或“string”。

The syntactic analyzer does not know whether or not you have a class named "var" in scope;语法分析器不知道您是否在范围内有一个名为“var”的类; "var" is treated not as a predefined type, but rather as just another name for just another type. “var” 不被视为预定义类型,而只是另一种类型的另一个名称。 Only if we cannot find a type in scope named "var" does the semantic analyzer then decide, oh, this must be an implicitly typed local.只有当我们在范围内找不到名为“var”的类型时,语义分析器才会决定,哦,这必须是隐式类型的本地。

The reason for this is because "var" was added in C# 3, and there might be C# 1 or 2 programs that use "var" as the name of a type.这是因为在 C# 3 中添加了“var”,并且可能有 C# 1 或 2 程序使用“var”作为类型的名称。 We did not want to break those programs.我们不想破坏这些程序。

不是对您的问题的精确答案,但实现相同效果的另一种(更简单)方法是使用 Syntax.ParseStatement:

Syntax.ParseStatement("var " + name);

To simplify answering questions like these, I've written a tool called Quoter that can generate syntax tree API calls for any given C# program:为了简化对此类问题的回答,我编写了一个名为 Quoter 的工具,它可以为任何给定的 C# 程序生成语法树 API 调用:

https://roslynquoter.azurewebsites.net https://roslynquoter.azurewebsites.net

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

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