为什么我们不能在 if 语句中定义变量? [英] Why can't we define a variable inside an if statement?

查看:61
本文介绍了为什么我们不能在 if 语句中定义变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这个问题以前有人回答过,但是if这个词经常出现,很难找到.

Maybe this question has been answered before, but the word if occurs so often it's hard to find it.

这个例子没有意义(表达式总是正确的),但它说明了我的问题.

The example doesn't make sense (the expression is always true), but it illustrates my question.

为什么此代码有效:

StringBuilder sb;
if ((sb = new StringBuilder("test")) != null) {
    Console.WriteLine(sb);
}

但这段代码不是:

if ((StringBuilder sb = new StringBuilder("test")) != null) {
    Console.WriteLine(sb);
}

我发现了一个关于 while 语句的类似问题.那里接受的答案说在 while 语句中,这意味着变量将在每个循环中定义.但对于我的 if 语句示例,情况并非如此.

I found a similar question regarding a while statement. The accepted answer there says that in a while statement, it would mean the variable would be defined in each loop. But for my if statement example, that isn't the case.

那么我们不允许这样做的原因是什么?

So what's the reason we are not allowed to do this?

推荐答案

这是因为 C# 语言规范的第 8.5.1 节.状态:

This is because section 8.5.1 of the C# language spec. states:

此外,局部变量声明中的变量初始值设定项与在声明之后立即插入的赋值语句完全对应.

Furthermore, a variable initializer in a local variable declaration corresponds exactly to an assignment statement that is inserted immediately after the declaration.

这基本上意味着,当您这样做时:

This basically means that, when you do:

StringBuilder sb = new StringBuilder("test")

实际上,您正在做与以下完全相同的事情:

You're, in effect, doing the exact same thing as:

StringBuilder sb; sb = new StringBuilder("test")

因此,您对 != null 的检查不再有返回值,因为赋值不是单个表达式,而是一个语句,它是一个本地-variable-declarator 由一个标识符后跟一个表达式组成.

As such, there is no longer a return value for your check against != null, as the assignment isn't a single expression, but rather a statement, which is a local-variable-declarator comprised of an identifier followed by an expression.

语言规范给出了这个例子,声明如下:

The language specification gives this example, stating that this:

void F() {
   int x = 1, y, z = x * 2;
}

完全等同于:

void F() {
   int x; x = 1;
   int y;
   int z; z = x * 2;
}

这篇关于为什么我们不能在 if 语句中定义变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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