C#中的匿名未附加块的值是什么? [英] What is the value of an anonymous unattached block in C#?

查看:30
本文介绍了C#中的匿名未附加块的值是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,您可以在未附加到任何其他语句的方法内部制作一个块.

In C# you can make a block inside of a method that is not attached to any other statement.

    public void TestMethod()
    {
        {
            string x = "test";
            string y = x;

            {
                int z = 42;
                int zz = z;
            }
        }
    }

此代码编译并运行,就像main方法中的括号不存在一样.还要注意块内的块.

This code compiles and runs just as if the braces inside the main method weren't there. Also notice the block inside of a block.

是否存在一种有价值的方案?我还没有找到任何东西,但很好奇听到别人的发现.

Is there a scenario where this would be valuable? I haven't found any yet, but am curious to hear of other people's findings.

推荐答案

作用域和垃圾回收:当您离开未附加的块时,其中声明的任何变量都将超出作用域.这样垃圾收集器就可以清理那些对象.

Scope and garbage collection: When you leave the unattached block, any variables declared in it go out of scope. That lets the garbage collector clean up those objects.

Ray Hayes 指出.NET垃圾收集器不会立即收集范围外的对象,因此范围界定是主要的好处.

Ray Hayes points out that the .NET garbage collector will not immediately collect the out-of-scope objects, so scoping is the main benefit.

这篇关于C#中的匿名未附加块的值是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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