简体   繁体   中英

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 . 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; I just thought that I would add that the reason for the error is because "var" is not a predefined type . A predefined type is something like "int" or "string".

The syntactic analyzer does not know whether or not you have a class named "var" in scope; "var" is treated not as a predefined type, but rather as just another name for just another type. 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.

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. 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:

https://roslynquoter.azurewebsites.net

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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