0

我的问题是关于在 vb.net 中使用 ByVal 的概念。

这是代码:

Private Sub ManipulateDetails()
Dim tObject1 as New customdatatype

tObject1.sName = "Stack"
tObject1.sLastName = "Over"

GetManipulateDetails(tObject1)

End Sub


Private Function GetManipulateDetails(ByVal tObject1 as customdatatype)

tObject1.sName = "Stack-Over-Flow"
tObject1.sLastName = "Flow-Over-Stack"
Return tObject1

End Function

在上面的代码片段中,我在 GetManipulateDetails 函数中将 tObject1 作为 ByVal 发送,当此子例程中的值发生更改时,返回的对象会操纵传递的实际对象。即,如果我在 ManipulateDetails 方法中快速观察对象,我可以看到被操纵的细节。此外,如果我在子例程函数中返回对象,则值将反映在传递的原始对象中。

因为即使没有从函数 GetManipulateDetails 返回对象,值也会发生变化,我很困惑这是否是因为 ByRef?或者还有其他一些机制正在使这项工作。

4

1 回答 1

3

It may be clearer if we use different names:

Private Sub ManipulateDetails()
Dim tObject1 as New customdatatype

tObject1.sName = "Stack"
tObject1.sLastName = "Over"

GetManipulateDetails(tObject1)

End Sub


Private Function GetManipulateDetails(ByVal tother as customdatatype) as customdatatype

tother.sName = "Stack-Over-Flow"
tother.sLastName = "Flow-Over-Stack"
Return tother

End Function

Before you call GetManipulateDetails, tObject1 is a reference to an object of type customdatatype. When you call GetManipulateDetails, tother gets a copy of tObject1. Importantly, what this means is that now, tObject1 and tother are both references to the same object. What was copied was the reference, not the object. Within GetManipulateDetails, it can use its copy of the reference to access the object and make changes to it.

ByVal parameters are always copied - but parameters are either value types or references. They're never reference types (aka objects) themselves.

于 2014-03-05T07:59:39.130 回答