简体   繁体   English

C#中的变量范围,Java

[英]Variable Scope in C#, Java

No, this is not my homework. 不,这不是我的功课。
(Because there is a stack of answer sheets beside me, waiting to be marked.) (因为我旁边有一叠答题纸,等待被标记。)

Q: If a local variable in a method has the same name as a variable in the main program, what will occur? 问:如果方法中的局部变量与主程序中的变量同名,会发生什么?
a) an error is generated a)生成错误
b) the variable in the main program is "hidden" until the method is finished executing b)主程序中的变量被“隐藏”,直到方法执行完毕
c) the variable in the main program will override the variable from the method c)主程序中的变量将覆盖方法中的变量
d) None of the above. d)以上都不是。

And the textbook answer is b, quite straightforward. 教科书答案是b,非常简单。

But on a second thought, is it really "hidden"? 但是,再想一想,它真的“隐藏”了吗?
As far as I know, in pure object-oriented languages like C# and Java, 据我所知,在纯粹的面向对象语言中,如C#和Java,
we can always use 我们总是可以使用

this.x

or 要么

MainProgram.x

for static variables. 对于静态变量。

So my question is: 所以我的问题是:
Can option b be considered true for C#? 对于C#,选项b是否可以被认为是真的? Why? 为什么?

Please share your thoughts. 请分享你的想法。

Yes, the local variable x hides (or more precisely, shadows - thanks to @pst) the member variable x within the scope of that method / block. 是的,局部变量x隐藏(或更确切地说, 阴影 - 感谢@pst)该方法/块范围内的成员变量x You can refer to the latter with its qualified name as this.x , to make life easier, but nevertheless the answer is correct. 您可以将后者的合格名称称为this.x ,以使生活更轻松,但答案是正确的。 A (fully) qualified name is not scope-dependent anymore so it can't be hidden or shadowed. (完全)限定名称不再依赖于范围,因此无法隐藏或隐藏。

I refer you to section 3.7.1 of the C# 4 specification, the beginning of which I quote here for your convenience: 我将向您介绍C#4规范的第3.7.1节,为方便起见,我在此引用其开头部分:

The scope of an entity typically encompasses more program text than the declaration space of the entity. 实体的范围通常包含比实体的声明空间更多的程序文本。 In particular, the scope of an entity may include declarations that introduce new declaration spaces containing entities of the same name. 特别是,实体的范围可能包括引入包含同名实体的新声明空间的声明。 Such declarations cause the original entity to become hidden . 此类声明会导致原始实体隐藏 Conversely, an entity is said to be visible when it is not hidden . 相反,当一个实体未被隐藏时,它被认为是可见的

Correctly understanding this portion of the specification requires that you understand the difference between the scope of an entity and its declaration space . 正确理解规范的这一部分要求您了解实体范围与其声明空间之间的区别。 The scope is the region of program text in which the entity may be referred to by its unqualified name. 范围是程序文本的区域,实体可以通过其不合格的名称来引用。 The declaration space is the region of program text in which an entity's name is unique. 声明空间是程序文本的区域,实体的名称在该区域中是唯一的。

Read the rest of section 3.7.1 for the details. 有关详细信息,请阅读3.7.1节的其余部分。

I note also that the specified term is "hidden", though "shadowed" is also frequently used. 我还注意到指定的术语是“隐藏的”,但也经常使用“阴影”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM