c# - 范围以及如何使用 VB.Net 缩小范围

标签 c# vb.net scope reflector

如果我想在 C# 中缩小变量的范围,我可以引入额外的大括号 - 即:

class Program
{
    static void Main(string[] args)
    {
        myClass x = new myClass();
        x.MyProperty = 1000;
        Console.WriteLine("x = " + x.MyProperty);

        {
            myClass y = new myClass();
            y.MyProperty = 2000;
            Console.WriteLine("y = " + y.MyProperty);
        }

        myClass y2 = new myClass();
        y2.MyProperty = 3000;
        Console.WriteLine("y2 = " + y2.MyProperty);

    }

    class myClass
    {

        public int MyProperty { get; set; }

    }
}

在 ide 中,我不能再在新大括号引入的范围之外引用 y。我原以为这意味着变量 y 可用于垃圾回收。

(有趣的是,当使用反射器查看编译后的代码时,似乎有或没有额外的大括号没有区别)

在使用 VB.net 时,有没有类似的方法来缩小范围?这对内部作用域中定义的变量何时可能被垃圾收集有任何影响吗?

最佳答案

有趣的是,developerFusion c#-vb.net 代码转换器转换

 {
    myClass y = new myClass();
    y.MyProperty = 2000;
    Console.WriteLine("y = " + y.MyProperty);
 }

If True Then
   Dim y As New [myClass]()
   y.MyProperty = 2000
   Console.WriteLine("y = " & y.MyProperty)
End If

作为限制范围的一种方式。我很惊讶它会记住 paintballbob's answer

关于c# - 范围以及如何使用 VB.Net 缩小范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1485621/

相关文章:

c# - MVVM-有没有一种方法可以在不使用数据绑定(bind)的情况下获取和设置文本框的文本?

vb.net - 使用默认形式 String.IsNullOrEmpty(str) 而不是 str.IsNullOrEmpty() 有什么意义吗?

haskell 树 : data constructor not in scope

powershell - 有没有更简单的方法来访问私有(private)范围变量?

c# - 如何在工具条按钮位置打开表单

C# - 如何利用 "INotifyPropertyChanged"更新集合类中的计算字段?

.net - 为什么 .NET Framework v1.1.4322 文件夹中缺少 "Microsoft.VisualBasic.Compatibility.dll"?

java - 将 json 解析值与用户输入的值进行匹配

c# - 调用任务后丢失 [ThreadStatic] 值

vb.net - 如何为数据集表中的每一行做一个?