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

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

问题描述

也许这个问题已经回答过了,但这个词如果时常常很难找到它。

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

这个例子没有意义(除权pression始终是真实的),但它说明了我的问题。

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

这是为什么code有效的:

Why is this code valid:

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

但是,这code不是:

But this code isn't:

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

我就发现了一个,而语句类似的问题。接受答案有说,在,而语句,这将意味着变量将在每个循环中定义。但是,对于我的如果语句的例子,事实并非如此。

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")

因此​​,不再有对支票针对一个返回值!=空,作为分配是不是一个单一的前pression,而是一份声明中,这是一个的局部变量声明的由一个标识符的后面跟着一个前pression

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天全站免登陆