VBA:如何测试对象相等性(两个变量是否引用同一个对象)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11254401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:41:07  来源:igfitidea点击:

VBA: how to test for object equality (whether two variables reference the same object)

oopvba

提问by Swiftslide

What is the operator or function to test whether two variables of the same custom object type refer to the same object? I've tried

测试相同自定义对象类型的两个变量是否引用同一个对象的运算符或函数是什么?我试过了

If myObject = yourObject Then

But get a runtime error 438 object doesn't support this property or method. I'm guessing that's telling me to override the '=' operator to test if all the fields of the two objects have the same value. But what I want is to test whether they are the same object.

但是得到运行时错误 438 对象不支持此属性或方法。我猜这告诉我要覆盖 '=' 运算符以测试两个对象的所有字段是否具有相同的值。但我想要的是测试它们是否是同一个对象。

回答by GSerg

I'm guessing that's telling me to override the '=' operator to test if all the fields of the two objects have the same value.

我猜这告诉我要覆盖 '=' 运算符以测试两个对象的所有字段是否具有相同的值。

No, it tells you the objects don't have a default property which would have been called otherwise, and the returned results compared.

不,它告诉您对象没有默认属性,否则会被调用,并且比较返回的结果。

You test reference equality with Is

您测试参考相等性 Is

If myObject Is yourObject Then 

回答by Dexterial

You need to serialize the objects somehow and then compare attribute by attribute values. The "is" operator is as dumb as it gets, it only matches if another object is the same instance assigned to the compared variable. I suggest using a jsonStringify library. I adapted one for my DexTools.xlam open source project https://github.com/dexterial/Dextools/tree/master/Mainstarting from the Parsing JSON in Excel VBApost. It has much more added features since I added quite a few other excel objects serialization/hashing options and it is made using the vba test driven development that DexTools incorporates. It is still work in progress so dont expect miracles

您需要以某种方式序列化对象,然后按属性值比较属性。“is”运算符很笨,只有在另一个对象是分配给比较变量的相同实例时才匹配。我建议使用 jsonStringify 库。我从解析 JSON in Excel VBA帖子开始,为我的 DexTools.xlam 开源项目https://github.com/dexterial/Dextools/tree/master/Main改编了一个。它具有更多附加功能,因为我添加了很多其他 excel 对象序列化/散列选项,并且它是使用 DexTools 集成的 vba 测试驱动开发制作的。它仍在进行中,所以不要指望奇迹