方法中的内部/嵌套作用域 [英] Inner/Nested Scope in Methods

查看:12
本文介绍了方法中的内部/嵌套作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名 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# 中(通常至少)没有必要这样做,但是(正如 Brandon Moore 所说),为什么不呢?

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屋!

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