Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#中的空白嵌套作用域?_C#_Scope - Fatal编程技术网

C#中的空白嵌套作用域?

C#中的空白嵌套作用域?,c#,scope,C#,Scope,今天,我碰巧在开放的地方添加了空白的花括号,似乎与语言一起工作,以创建一种嵌套的作用域,除了嵌套之外,它不适用于做任何事情 public void Example() { int b = 3; //curly braces just floating in the open -- allowed by compiler { int c = 2; } //error b = c; } 我的假设正确吗?这只是一种将事物显式嵌套在其

今天,我碰巧在开放的地方添加了空白的花括号,似乎与语言一起工作,以创建一种嵌套的作用域,除了嵌套之外,它不适用于做任何事情

public void Example()
{
    int b = 3;

    //curly braces just floating in the open -- allowed by compiler
    {
        int c = 2;
    }

    //error
    b = c;
}

我的假设正确吗?这只是一种将事物显式嵌套在其自身范围内的方法?

大括号创建局部范围。考虑这个代码:

        int b = 3;

        {
            int c = 2;
            Console.WriteLine("First Scope:");
            Console.WriteLine(c); //will print 2
        }

        {
            int c = 3;
            Console.WriteLine("Second Scope:");
            Console.WriteLine(c); //will print 3
        }

        //error
        b = c;
  • 第二个大括号中的c变量将创建一个新的变量实例
  • 第一个和第二个花括号中的c变量没有关系
  • 将无法到达大括号外的变量c赋值,并将创建语法错误

类似的帖子:

Yes:这是一个创建新范围的block语句。实际上,它与在
if(cond){}