[C#]在块内部制作对象的实例也在块之外工作? [英] [C#] making instance of object inside block works also outside the block ?

查看:71
本文介绍了[C#]在块内部制作对象的实例也在块之外工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我想知道这是如何工作的:

Hi. Im wondering how this worked:

using System;

namespace ConsoleApplication2
{
    class Program
    {
        public static void Main()
        {
            A kick = null;

            {
                kick = new A();
            } // End of the block 

            kick.HelloFromA(); // How I am able still to access it ? 
        }
    }

    class A
    {
        public void HelloFromA()
        {
            Console.WriteLine("Hello from A");
        }
    }
}





垃圾收集器不应该破坏A对象我的A型参考变量指向?



我尝试过的事情:



在CodeProject.com中提出问题



Shouldn't the gerbage collector destroy the A object to which my reference variable of type A is pointing to ?

What I have tried:

Asking question here in CodeProject.com

推荐答案

'kick'在main方法的块中声明,包括任何嵌套块。所以,你的代码是有效的。反过来说,内部区块中的声明在外部区块中是未知的:

'kick' is declared in the main method's block and that includes any nested blocks. So, your code is valid. The other way around, a declaration in an 'inner block' is not known in an 'outer block':
public static void Main()
{
    {
        A kick = null;
        kick = new A();
    }
 
    kick.HelloFromA(); // Here you can't access kick...
}



垃圾收集器在超出范围后清除踢,但你不知道何时(很可能不是立即)。


The garbage collector cleans up kick after it goes 'out of scope' but you just don't know when (most likely not immediately).


当执行离开它所定义的块时,变量超出范围,

而不是分配给它的块。 kick 在Main方法中定义,并且在整个Main方法中都可见,甚至是内部块。它与您分配 kick 的值无关。
A variable goes out of scope when execution leaves the block it was defined in,
NOT the block where it was assigned to. kick was defined in the Main method and will be visible through out the entire Main method, even inner blocks. It has nothing at all to do with where you assigned kick its value.


这篇关于[C#]在块内部制作对象的实例也在块之外工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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