问题
Until today, I thought that the following two notations are the same (edit: Dim
was replaced by Property
)
Property arrayVariable() As Object
Property arrayVariable As Object()
Today I found that former one throws error Option Strict On disallows late binding.
while the latter compiles OK in expression dictionary1.TryGetValue(CStr(arrayVariable(0)), result)
.
Please what is the difference between them?
I would always use the second notation if it also allowed to specify the array dimensions. It doesn't, so I stuck with the first form (less clean one, because part of type specification - parenthesis - are before As
) in order to be consistent across declarations. And now I see that even the first one isn't universal...
It really looks like a weak point of Visual Basic that two forms exist for one thing and their usage is not straightforward but has catches like this.
Full source code reproducing the issue:
Public Class Class1
Dim _A1() As Object
Dim _A2() As Object
ReadOnly Property A1() As Object ' 1st form of declaration
Get
Return _A1
End Get
End Property
ReadOnly Property A2 As Object() ' 2nd form of declaration
Get
Return _A2
End Get
End Property
End Class
Sub Main()
Dim c1 As New Class1
Dim d1 As New Dictionary(Of String, String)
Dim value As String = ""
d1.TryGetValue(CStr(c1.A1(0)), value) '<- Option Strict On disallows late binding.
d1.TryGetValue(CStr(c1.A2(0)), value) '<- No error here.
End Sub
回答1:
The problem is that they are Properties so the ()
is ignored as an Array specifier and thinks of it as an empty parameter collection. Look at how the compiler see them - even the compiler thinks you had an Object and not a Object()
and so in your example the A1(0)
is an index of an object which is not defined so it thinks you have done some late binding and made it accept an array.
If you are not using a Property and an Object type either declaration is valid.
Dim data() As String
Same as
Dim data As String()
If you highlight either variable the intellisence shows you:
Dim data() As String
回答2:
Here's the minimum amount of code required to replicate your issue:
Dim y As Object
Dim x = y(0)
This has nothing to do with the declaration of arrays. You're just trying to convert an Object
to an array which option strict doesn't allow.
回答3:
Additional notes:
(not sure why this has been downvoted)
Changing Object
to Integer
reveals the first form mentioned in question is not taken as declaration.
Public Class Class1
Dim _A1 As Integer()
Dim _A2 As Integer()
ReadOnly Property A1() As Integer
Get
Return _A1
' error at above line: Value of type '1-dimensional array of Integer' cannot
' be converted to 'Integer'.
End Get
End Property
ReadOnly Property A2 As Integer()
Get
Return _A2
End Get
End Property
End Class
Proper way is
ReadOnly Property A1() As Integer()
来源:https://stackoverflow.com/questions/27883578/arrayvariable-as-object-vs-arrayvariable-as-object-not-the-same-in-proper