if语句后面的变量声明 [英] Variable declarations following if statements

查看:224
本文介绍了if语句后面的变量声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个论坛上出现了一个问题,我知道如何修复它,但它揭示了我特有的编译器功能。此人收到错误嵌入式语句不能是声明或标签声明,因为他们在没有括号的if语句后声明了变量。这不是他们的意图,但是他们在if语句之后立即注释掉了代码行,这使得变量声明成为执行的事实上的代码行。无论如何,这就是背景,这让我想到了这一点。

An issue came up on another forum and I knew how to fix it, but it revealed a feature of the compiler peculiar to me. The person was getting the error "Embedded statement cannot be a declaration or labeled statement" because they had a declaration of a variable following an if statement with no brackets. That was not their intent, but they had commented out the line of code immediately following the if statement, which made the variable declaration the de facto line of code to execute. Anyway, that's the background, which brings me to this.

以下代码是非法的

if (true)
    int i = 7;

但是,如果你把它包在括号中,那一切都是合法的。

However, if you wrap that in brackets, it's all legal.

if (true)
{
    int i = 7;
}

两段代码都没用。然而第二个是好的。这种行为的具体解释是什么?

Neither piece of code is useful. Yet the second one is OK. What specifically is the explanation for this behavior?

推荐答案

C#语言规范区分三种类型的语句(更多细节见第8章)。一般来说,您可以拥有以下声明:

The C# language specification distinguishes between three types of statements (see chapter 8 for more details). In general you can have these statements:


  • labeled-statement - 我猜这是旧的 - 老式转到声明

  • 声明声明 - 这将是一个变量声明

  • 嵌入式声明 - 其中包括几乎所有剩余的陈述

  • labeled-statement - my guess that this is for the old-fashioned goto statement
  • declaration-statement - which would be a variable declaration
  • embedded-statement - which includes pretty much all the remaining statements

if 语句主体必须是 embedded-statement ,这解释了为什么第一个版本的代码不起作用。以下是规范中的 if 的语法(第8.7.1节):

In the if statement the body has to be embedded-statement, which explains why the first version of the code doesn't work. Here is the syntax of if from the specification (section 8.7.1):


if( boolean-expression embedded-statement

if( boolean-expression embedded-statement else embedded-statement

if ( boolean-expression ) embedded-statement
if ( boolean-expression ) embedded-statement else embedded-statement

变量声明是 declaration-statement ,所以它不能出现在体内。如果您将声明括在括号中,您将获得一个语句块,这是一个嵌入式语句(因此它可以出现在该位置)。

A variable declaration is declaration-statement, so it cannot appear in the body. If you enclose the declaration in brackets, you'll get a statement block, which is an embedded-statement (and so it can appear in that position).

这篇关于if语句后面的变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆