gpt4 book ai didi

c# - ‘finally’ block 可以更改其 ‘try’ block 的返回值吗?

转载 作者:行者123 更新时间:2023-11-30 23:01:36 26 4
gpt4 key购买 nike

我期望 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???
}
}

最佳答案

我将通过代码注释引导您完成它。

//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 block 的影响。

关于c# - ‘finally’ block 可以更改其 ‘try’ block 的返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50957455/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com