.net 最终理解对象引用
这可能是一个重复的问题,但我没有在网上得到它。我有一个返回类型为datatable的函数.net 最终理解对象引用,.net,oop,object,coding-style,business-logic,.net,Oop,Object,Coding Style,Business Logic,这可能是一个重复的问题,但我没有在网上得到它。我有一个返回类型为datatable的函数 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
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中
因此,在本例中,当我返回datatable对象时,如果我最后写入datatable对象=nothing,那么为什么返回的datatable对象没有得到任何东西。
我得到了正确的结果,但我的问题是,如果datatable对象引用类型,那么为什么我的datatable最终没有得到任何内容。因为当您将本地引用设置为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
想一想。当您执行
dtloclencence=nothing
时,您将使dtloclencence
无效,而不是实际的DataTable对象。还有一个对实际数据表的引用可能不那么明显,即函数本身(通过Return
语句),它防止数据表超出范围,从而被GC收集。您能澄清一下吗?您希望返回值是什么?调用此函数时得到了什么?我得到了正确的结果,先生。我只是想知道为什么我的datatable即使最后我写=nothing也不返回nothing?这意味着在return语句中它不返回对象引用,它只返回该对象的值?不,同样,该函数只是作为对实际内存对象的引用,就像dtloclencence
。可以用指针来考虑(如果您使用过C++)。如果有两个指针a和b,它们都引用同一个内存对象,并且您将a设置为null,则不会清除内存对象或b。引用变量不是严格意义上的指针(如C++中),但基本概念是相同的。这意味着在return语句中,它不返回对象引用,它只返回该对象的值?@Terror.Blade-对于值类型,它只返回值。对于引用类型,它返回一个引用。DataTable是一种引用类型,因此在上面的伪代码中,result和DTLOCELECTENCE都是对同一对象的引用。将其中一个引用设置为Nothing/null不会影响另一个引用。