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

查看:26
本文介绍了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 - 我猜这是老式的 goto 语句
  • declaration-statement - 这将是一个变量声明
  • embedded-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,这解释了为什么代码的第一个版本不起作用.以下是规范(第 8.7.1 节)中 if 的语法:

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 ) 嵌入式语句
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天全站免登陆