[英]Different behavior between different String Array initialisation
If I fill an array like 如果我像这样填充数组
Return New String() {"A", "B"}
and return it in a property to display its elements into a combobox 并将其返回到属性中以将其元素显示到组合框中
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
It works fine. 工作正常。 But if I change the initialization to
但是如果我将初始化更改为
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
my combobox is empty (I dont get any error though). 我的组合框为空(尽管我没有收到任何错误)。 Could anyone explain that to me?
有人可以向我解释吗?
In the second example, if you want something to get back from the property then you need to fill the array. 在第二个示例中,如果您希望从属性中获取某些东西,则需要填充数组。
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
However, given the context, returning a fixed set of constant strings, the first approach seems to be preferable. 但是,在给定上下文的情况下,返回固定的一组常量字符串,第一种方法似乎是更可取的。 (Less code and the array size is calculated automatically).
(更少的代码和数组大小是自动计算的)。
If the context changes and you find yourself the need to return a variable number of strings then consider to use as a return type a List(Of String)
如果上下文发生变化,并且您发现自己需要返回可变数量的字符串,则可以考虑将
List(Of String)
用作返回类型List(Of String)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.