arrayVariable() As Object vs. arrayVariable As Object() – not the same in Property declaration?
直到今天,我还认为以下两个符号是相同的(编辑:
1 2 | Property arrayVariable() As Object Property arrayVariable As Object() |
今天我发现前者抛出错误
请问它们之间有什么区别?
如果还允许指定数组尺寸,我将始终使用第二种表示法。事实并非如此,所以我坚持使用第一种形式(不太干净的形式,因为类型说明的一部分-括号-在
看起来像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 |
问题在于它们是属性,因此
如果您不使用属性和对象类型,则任一声明均有效。
1 | Dim data() As String |
与
相同
1 | Dim data As String() |
如果您突出显示任何一个变量,那么智力将显示:
1 | Dim data() As String |
补充说明:
(不确定为什么要拒??绝投票)
将
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) |
这与数组的声明无关。您只是想将