不同String Array初始化之间的不同行为

时间:2014-08-14 14:07:21

标签: arrays vb.net

如果我填充像

这样的数组
Return New String() {"A", "B"}

并将其返回到属性中以将其元素显示为组合框

Public Class Test
    Public ReadOnly Property TLTeams As String()
        Get
            'Return New String() {"A", "B"}
        End Get
    End Property
End Class

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim t As New Test
        For i As Integer = 0 To t.TLTeams.Length
            ComboBox1.Items.Add(t.TLTeams(i).ToString)
        Next i
    End Sub
End Class

工作正常。 但是,如果我将初始化更改为

Public ReadOnly Property TLTeams As String()
    Get
        Dim a As String = "A"
        Dim b As String = "B"
        Dim ArS(1) As String
        Return ArS
    End Get
End Property

我的组合框是空的(虽然我没有得到任何错误)。有谁可以向我解释一下?

1 个答案:

答案 0 :(得分:0)

在第二个示例中,如果您想要从属性返回某些内容,则需要填充数组。

Public ReadOnly Property TLTeams As String()
    Get
        Dim a As String = "A"
        Dim b As String = "B"
        Dim ArS(1) As String
        ArS(0) = a
        ArS(1) = b
        Return ArS
    End Get
End Property

但是,考虑到上下文,返回一组固定的常量字符串,第一种方法似乎更可取。 (更少的代码和数组大小自动计算)。

如果上下文发生变化并且您发现自己需要返回可变数量的字符串,那么请考虑将其用作返回类型List(Of String)