关于arrays:array Variable()作为对象vs. array Variable As Object()–属性声明不一样吗?

arrayVariable() As Object vs. arrayVariable As Object() – not the same in Property declaration?

直到今天,我还认为以下两个符号是相同的(编辑:DimProperty代替)

1
2
Property arrayVariable() As Object
Property arrayVariable As Object()

今天我发现前者抛出错误Option Strict On disallows late binding.,而后者在表达式dictionary1.TryGetValue(CStr(arrayVariable(0)), result)中编译正常。

请问它们之间有什么区别?

如果还允许指定数组尺寸,我将始终使用第二种表示法。事实并非如此,所以我坚持使用第一种形式(不太干净的形式,因为类型说明的一部分-括号-在As之前),以便在声明之间保持一致。现在我看到,即使第一个也不通用...

看起来像Visual Basic的弱点,一件事情同时存在两种形式,它们的用法并不简单,但有这样的陷阱。

再现问题的完整源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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


问题在于它们是属性,因此()被忽略为数组说明符,并将其视为空参数集合。看一下编译器如何看待它们-甚至编译器都认为您有一个Object而不是Object(),因此在您的示例中,A1(0)是未定义对象的索引,因此认为您做了一些后期绑定并使其接受数组。

如果您不使用属性和对象类型,则任一声明均有效。

1
Dim data() As String

相同

1
Dim data As String()

如果您突出显示任何一个变量,那么智力将显示:

1
 Dim data() As String

补充说明:

(不确定为什么要拒??绝投票)

Object更改为Integer时,发现所提及的第一种形式不作为声明。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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

正确的方法是

1
    ReadOnly Property A1() As Integer()


以下是复制您的问题所需的最少代码量:

1
2
Dim y As Object
Dim x = y(0)

这与数组的声明无关。您只是想将Object转换为严格选项不允许的数组。