ByRef 不能在 VBA 中使用来自类的值类型 [英] ByRef not working in VBA with value type from a class

查看:43
本文介绍了ByRef 不能在 VBA 中使用来自类的值类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用 ByRef 成功,直到现在.我需要一个函数来修改类对象中的 Double.为了说明这一点,请考虑以下程序.

I always used ByRef successfully, until now. I need a function to modify a Double from a class-object. To illustrate, consider the following program.

Class1.cls:
Public d As Double

Sub Test()
    Dim c As Class1, d As Double
    Set c = New Class1

    c.d = 5
    d = 5

    ChangeVar c.d
    ChangeVar d

    Debug.Print c.d
    Debug.Print d
End Sub

Sub ChangeVar(ByRef d As Double)
    d = 10
End Sub

出乎我的意料,上面的例子会输出

For my surprise, the above example will output

5
10

有人吗?

推荐答案

在幕后 aClassInstance.publicVariable 被封装为一个隐藏属性 get/let 对,因此传递 ByRef 传递隐藏的 get 属性返回值的地址,而不是类中声明的底层变量.

Under the hood aClassInstance.publicVariable is encapsulated as a hidden property get/let pair, so passing ByRef is passing the address of the hidden get properties return value, not the underlying variable declared in the class.

您可以通过检查类中 d 的两种形式的地址来测试这一点;他们会有所不同

You can test this by examining the addresses of the 2 forms of d within the class; they will be different

(class_init)
debug.? " d address=" & VarPtr(d)
debug.? ".d address=" & VarPtr(me.d)

这篇关于ByRef 不能在 VBA 中使用来自类的值类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆