“最终”代码块能否更改其“尝试”代码块的返回值?

时间:2018-06-20 21:40:24

标签: c#

我期望下面的代码中的obj为空,因为我的理解是对象是通过引用返回的。有人可以解释为什么obj不为空吗?

public class Example
{
    private static ArrayList obj;

    public static ArrayList GetObj()
    {
        try
        {
            obj = new ArrayList();
            return obj;
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            obj = null;
        }
    }
}

public class MainProgram
{
    public static void SomeMethod()
    {
        ArrayList obj;
        obj = Example.GetObj(); // Why is obj not null???
    }
}

1 个答案:

答案 0 :(得分:2)

我将通过代码注释逐步指导您。

//This reserves a memory location to store a reference to an ArrayList
private static ArrayList obj;  

public static ArrayList GetObj()
{
    try
    {
        //This instantiates a new ArrayList and stores a reference to it in obj
        obj = new ArrayList();

        //This creates a copy of the reference stored in obj and returns it to the caller
        return obj;
    }
    catch (Exception e)
    {
        throw e;
    }
    finally
    {
        //This sets the reference stored in obj to null. This does not affect the copy of the reference that was returned earlier
        obj = null;
    }
}

public static void SomeMethod()
{
    //This reserves a different memory location that can store a reference to an ArrayList.
    //Note that this exists in parallel with the static field named obj
    ArrayList obj;

    //This retrieves the reference to the ArrayList that was returned and stores it in the local (not static) variable obj
    obj = Example.GetObj(); 
}

最后,您的局部变量obj收到ArrayList引用的副本,并且不受finally块的影响。