Object Visual basic 6内置函数的默认属性
Visual Basic具有默认属性,在计算表达式时有时会隐式调用这些属性。然而,我似乎在默认属性的隐式执行中遇到了一个矛盾。项目布局如下所示: 类别1: 类别2: 表格1: MsgBox语句将隐式调用x的默认值(在class1上进行测试),并进一步调用该默认值(在class2上进行测试),从而在屏幕上显示“hello world”。然而,Debug.Print语句并没有这样做,通过跟随调试器,可以看到只调用了第一个默认值(在class1上) 我已经验证了许多内置函数,如MsgBox/RTrim/LTrim,都表现出这种行为,并且任何自写方法或类方法都不会这样做;但我无法解释为什么会发生这种情况?这根本不是内置函数的“行为”,而是取决于COM将对象引用和变量转换为字符串的方式。这还与Set和Let语言关键字和表达式求值(尤其是括号)有关。考虑这个示例代码:Object Visual basic 6内置函数的默认属性,object,properties,vb6,default-value,Object,Properties,Vb6,Default Value,Visual Basic具有默认属性,在计算表达式时有时会隐式调用这些属性。然而,我似乎在默认属性的隐式执行中遇到了一个矛盾。项目布局如下所示: 类别1: 类别2: 表格1: MsgBox语句将隐式调用x的默认值(在class1上进行测试),并进一步调用该默认值(在class2上进行测试),从而在屏幕上显示“hello world”。然而,Debug.Print语句并没有这样做,通过跟随调试器,可以看到只调用了第一个默认值(在class1上) 我已经验证了许多内置函数,如MsgBox/RTrim
Private Sub Form_Load()
Dim x As Class1
Dim v As Variant
Dim s As String
Set x = New Class1
Set v = x ' None
Let v = x ' Once
Set v = (x) ' Once
Let v = (x) ' Twice
's = x ' Compile error: Type mismatch
Set v = x
s = v ' Twice
s = CVar(x) ' Twice
MsgBox x
'Debug.Print CStr(x) ' Compile error: Type mismatch
'Debug.Print CVar(x) ' Run-time error: Type mismatch
Debug.Print CStr(CVar(x)) ' Twice
pvTest1 x
End Sub
Private Function pvTest1(ByVal o As Variant)
'Debug.Print o ' Run-time error: Type mismatch
Debug.Print CStr(o) ' Twice
End Function
请注意,将对象引用转换为字符串是一个编译时错误(CStr(x)调用),而包含引用的变量(IDispatch变量)转换得很好(s=v)。最后一个赋值将尽可能深地“展开”默认属性,而默认属性的计算结果为IDispatch(调用Invoke,DISPID设置为-1)
简而言之:如果您有一个对对象的引用,并且需要根据“原始”数据类型(例如字符串)的值反复计算默认属性,请使用CStr(CVar(x))(或CInt(CVar…)等)
property test -> string "hello world" (default)
Dim x As New Class2
MsgBox x
Debug.Print x
Private Sub Form_Load()
Dim x As Class1
Dim v As Variant
Dim s As String
Set x = New Class1
Set v = x ' None
Let v = x ' Once
Set v = (x) ' Once
Let v = (x) ' Twice
's = x ' Compile error: Type mismatch
Set v = x
s = v ' Twice
s = CVar(x) ' Twice
MsgBox x
'Debug.Print CStr(x) ' Compile error: Type mismatch
'Debug.Print CVar(x) ' Run-time error: Type mismatch
Debug.Print CStr(CVar(x)) ' Twice
pvTest1 x
End Sub
Private Function pvTest1(ByVal o As Variant)
'Debug.Print o ' Run-time error: Type mismatch
Debug.Print CStr(o) ' Twice
End Function