使用VB.net使用“新关键字"添加到数组 [英] Adding to an array using the New Keyword using VB.net
问题描述
我的班级设置如下:
I have a class set up as follows:
Public Class Tags
Public Sub New()
End Sub
Public Sub New(ByVal sTagName As String, _
ByVal sTagValue As String)
_tagName = sTagName
_tagValue = sTagValue
End Sub
Private _tagName As String
Public ReadOnly Property TagName() As String
Get
Return _tagName
End Get
End Property
Private _tagValue As String
Public ReadOnly Property TagValue() As String
Get
Return _tagValue
End Get
End Property
End Class
我有一个调用的函数,该函数将加载标签数组.
到目前为止,我是这个
I have a function I call that will load an array of Tags.
What I have so far is this
Public Class WMAID3Tag.vb
dim aryOfTags as Tags()
public function GetTags(ByVal fn as String) as Tags()
' Do some stuff to get a tagName and tagValue
aryOfTags = New Tags() {New Tags(tagName, tagValue)
' Look for more tags
aryOfTags = New Tags() {New Tags(tagName, tagValue)
' Found all the tags there are
Return aryOfTags
End Function
End Class
我遇到的问题是aryOfTags永远不会超过1个元素.
The problem I am having is that aryOfTags never grows beyond 1 element. Each new tag found simply replaces the last.
推荐答案
原因是在Function
中
The reason is that in the Function
public function GetTags(ByVal fn as String) as Tags()
' Do some stuff to get a tagName and tagValue
aryOfTags = New Tags() {New Tags(tagName, tagValue)
' Look for more tags
aryOfTags = New Tags() {New Tags(tagName, tagValue)
' Found all the tags there are
Return aryOfTags
End Function
在寻找更多标签下,为aryOfTags分配了一个新的标签数组,该数组替换了第一步中已分配的标签数组.因此,只有aryOfTags仅包含第二步中分配的一个元素.
两个返回两个标签,可以进行以下修改.
Under Look for more tags, An new array of tags is assigned to aryOfTags, which replaces the array of tags already assigned under the first step. So, only aryOfTags contains only one element assigned in the second step.
Two return two tags, the following modification can be done.
Public Class WMAID3Tag.vb
dim aryOfTags(1) as Tags
public function GetTags(ByVal fn as String) as Tags()
' Do some stuff to get a tagName and tagValue
aryOfTags(0) = New Tags(tagName, tagValue)
' Look for more tags
aryOfTags(1) = New Tags(tagName, tagValue)
' Found all the tags there are
Return aryOfTags
End Function
End Class
但是,最好使用List动态分配元素数量,而无需先定义大小.在上面的函数中,数组的大小声明为2号.如果期望更多,则将相应地确定大小.
使用List的功能如下
However, it is preferable to use List to dynamically assign number of elements without first defining the size. In the above function the size of array is declared as 2 Nos. If more are expected, then size shall be fixed accordingly.
The function using List is as follows
public function GetTagsList(ByVal fn as String) as List(Of Tags)
dim listOfTags as new List(Of Tags)
' Do some stuff to get a tagName and tagValue
listOfTags.Add(New Tags("tag1", "value1"))
' Look for more tags
listOfTags.Add(New Tags("tag2", "value2"))
listOfTags.Add(New Tags("tag3", "value3"))
' Found all the tags there are
Return listOfTags
End Function
这篇关于使用VB.net使用“新关键字"添加到数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!