【问题标题】:Blank Nested Scopes In C#?C# 中的空白嵌套范围?
【发布时间】:2021-03-13 00:20:53
【问题描述】:

今天,我碰巧在公开的地方添加了似乎可以与该语言一起使用的空白花括号,以创建一种嵌套范围区域,除了嵌套之外不涉及任何其他操作,

public void Example()
{
    int b = 3;

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

    //error
    b = c;
}

我的假设是否正确,它只是一种将事物显式嵌套在自己范围内的方法?

【问题讨论】:

标签: c# scope


【解决方案1】:

花括号创建局部范围。考虑这段代码:

        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 赋值将无法到达,并会产生语法错误

类似帖子:https://social.microsoft.com/Forums/Windows/es-ES/6ce386f2-f27d-42cd-b031-8664b92f8cae/c-curly-braces-without-head?forum=csharpgeneral

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多