【问题标题】:Understanding Finally with Object Reference最终理解对象引用
【发布时间】:2013-12-17 02:43:43
【问题描述】:

这可能是一个重复的问题,但我没有在网上得到它。我有一个返回类型是数据表的函数。

Function a() returns datatable

Dim DtLocLiecence as datatable
try
--- in this part i get value in the datatable

--and i am now returning datatable 

return DtLocLiecence

catch ex

finally

DtLocLiecence = nothing
end try

end function

现在我们知道 datatable 是一个引用类型,这意味着 对象 a =1 对象 b 如果我们写 b=a 然后 a 的引用保存在 b 中

所以在这种情况下,当我返回数据表对象时,最后如果我写那个数据表对象= 什么都没有,那么为什么我返回的数据表对象什么都没有。 我得到了正确的结果,但我的问题是如果数据表对象引用类型,那么为什么我的数据表最终没有得到任何结果。

【问题讨论】:

  • 你能澄清一下吗?您期望返回值是什么?调用此函数时会得到什么?
  • 我得到了正确的结果,先生。我只是想知道为什么我的数据表没有返回任何东西,即使我最后写了=nothing

标签: .net oop object coding-style business-logic


【解决方案1】:

考虑一下。当您执行DtLocLiecence = nothing 时,您将取消DtLocLiecence 而不是实际的DataTable 对象。还有另一个对实际 DataTable 的引用可能不那么明显,即函数本身(通过Return 语句),它使 DataTable 不会超出范围并因此被 GC 收集。

【讨论】:

  • 所以这意味着在return语句中它不返回对象引用它只返回该对象的值?
  • 不,这个函数只是作为对实际内存对象的引用,就像DtLocLiecence一样。用指针来考虑它(如果您使用过 C++)。如果有两个指针 a 和 b,它们都引用同一个内存对象,并且您将 a 设置为 null,则它不会清除内存对象或 b。引用变量不是严格意义上的指针(如在 C++ 中),但基本概念是相同的。
【解决方案2】:

因为当您将本地引用设置为 null 时,该值已经返回。也许如下思考可能会帮助您理解正在发生的事情,在一种假设语言中,函数的返回值在其参数列表中指定:

Function a(ReturnValue result as datatable) 
    Dim DtLocLiecence as datatable
    try
        --- in this part i get value in the datatable

        --and i am now returning datatable 

        result = DtLocLiecence
        return

    catch ex

    finally
        DtLocLiecence = nothing ' No effect on result
    end try


end function

【讨论】:

  • 所以这意味着在 return 语句中它不返回对象引用它只返回该对象的值?
  • @Terror.Blade - 对于值类型,它只返回值。对于引用类型,它返回一个引用。 DataTable 是引用类型,所以在上面的伪代码中,result 和 DtLocLiecence 都是对同一个对象的引用。将引用之一设置为 Nothing / null 不会影响另一个引用。
猜你喜欢
  • 2020-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-06-16
  • 1970-01-01
  • 2011-01-20
  • 1970-01-01
  • 2023-03-12
  • 2017-05-25
相关资源
最近更新 更多