如何在 Locals 窗口中获取实现接口的类的属性值? [英] How to get property values of classes that implement an interface in the Locals window?
问题描述
这真的很困扰我并阻碍了我的开发/调试.每当我声明我正在实现的接口的变量类型时,Locals 窗口都不会显示它的属性值.相反,它只是读取
This is really bothering me and hindering my development/debugging. Whenever I declare a variable type of the interface I'm implementing, the Locals Window doesn't show it's property values. Instead it just reads
对象不支持该属性或方法
Object doesn't support this property or method
这很愚蠢,因为它确实如此.事实上,它必须履行与接口的合同.
Which is silly, because it absolutely does. In fact it has to in order to fulfill its contract with the Interface.
如果我将变量声明为接口的具体实现,则窗口将按预期工作.然而,这完全违背了从一开始就对抽象进行编码的目的.
If I declare the variable as the concrete implementation of the interface, the window works as expected. However, that completely defeats the purpose of coding to the abstraction to begin with.
如何让本地窗口正确显示类的属性值?
最小、完整且可验证的示例:
创建一个 IClass
类以用作接口.
Create an IClass
class to use as an interface.
Option Explicit
Public Property Get Name() As String
End Property
创建一个实现接口的Class1
.
Option Explicit
Implements IClass
Public Property Get Name() As String
Name = "Class1"
End Property
Private Property Get IClass_Name() As String
IClass_Name = Name
End Property
最后,使用常规 .bas 模块中的一些测试代码来说明问题.
And lastly, some test code in a regular .bas module to illustrate the issue.
Option Explicit
Public Sub test()
Dim x As Class1
Dim y As IClass
Set x = New Class1
Debug.Print x.Name
Set y = New Class1
Debug.Print y.Name
Stop
End Sub
推荐答案
我可能是错的,但我认为这可能与类在 VBA 中的实例化方式有关.
I could be wrong, but I think this may be something to do with the way classes are instantiated in VBA.
例如:
Dim oClass1 as Class1
Set oClass1 = new Class1
不同于
Dim oClass1 as New Class1
在第二种情况下,我相信在访问属性之前不会调用构造函数.
In the second case I believe the constructor doesn't get called until the property is accessed.
如果您尝试此操作,则会在 Watch 窗口中看到该属性.请注意 IClass 的新功能 - 仅用于演示 - 我知道这不是这样做的方法 :)
If you try this, it is sees the property in the Watch window. Notice the New for the IClass - just for Demonstration - I know its not the way to do that :)
Public Sub test1()
Dim x As Class1
Dim y As IClass
Set y = New IClass
Set x = New Class1
Debug.Print x.Name
Debug.Print y.Name
Stop
End Sub
我怀疑它与此有关,监视窗口需要这个......也许......
I suspect its something to do with that and the watch window requires this ... maybe...
这篇关于如何在 Locals 窗口中获取实现接口的类的属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!