How do I declare a var variable with Roslyn?

淺唱寂寞╮ 提交于 2019-11-30 01:31:22

问题


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"


回答1:


I'd use:

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



回答2:


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.




回答3:


Not a precise answer to your question, but another (and simpler) way to achieve the same affect would be to use Syntax.ParseStatement:

Syntax.ParseStatement("var " + name);



回答4:


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:

http://blogs.msdn.com/b/kirillosenkov/archive/2012/07/22/roslyn-code-quoter-tool-generating-syntax-tree-api-calls-for-any-c-program.aspx



来源:https://stackoverflow.com/questions/8400248/how-do-i-declare-a-var-variable-with-roslyn

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!