方法的内部/嵌套范围 [英] Inner/Nested Scope in Methods
问题描述
我是一位C#开发人员,长期从事该语言的开发。
I am a C# developer who has been working with the language for a long time.
我想知道为什么语言允许嵌套/内部作用域。
I am wondering why the langauge allows nested/inner scopes for functions.
以下是我的意思的示例:
Here is an example of what I mean:
public int InnerScopeMethod()
{
int i = 10;
//Inner Scope
{
int j = 100;//j will not work outside of the scope.
i *= j;
}//Scope Ends Here
//j = 10 /// This Will Cause Error.
return i;
}
如您所见,方法主体具有匿名或未命名范围,它是在C#4中是合法的。
As you can see the method body has an anonymous or unnamed scope and it is legal in C# 4.
我想知道为什么在这里吗?
I want to know why is it here? Is this just for providing small scopes for variables or it has other uses?
任何帮助将不胜感激。
推荐答案
(通常至少)没有必要在C#中执行此操作,但是随后(如布兰登·摩尔所说),为什么不呢?
It (usually at least) isn't necessary to do this in C#, but then (as Brandon Moore said), why not?
一个原因可能是某些变量仅在有限的时间内有效,然后将其放入范围内,可以确保没有人以后会意外使用它们。
One reason could be that certain variables only have a limited time where they are valid, and by putting that variable inside a scope, you make sure that noone can accidentally use them later.
此外,C#基于C,这种构造非常有用。在C语言中,变量只能在作用域的开始处声明,因此,如果您只需要在一个地方使用一个临时变量(例如循环索引),则可以使用长方法来完成类似您编写的操作。
Additionally, C# is based on C, where this construct is very useful. In C, variables can only be declared at the start of a scope, so something like what you wrote can be done in long methods if you only need a temporary variable at one place (ex. a loop index).
这篇关于方法的内部/嵌套范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!