vb.net 使用List(Of)时如何添加项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8737516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add item when using List (Of)?
提问by JADE
I created a class where i declared some properties.
我创建了一个类,我在其中声明了一些属性。
Public Class BlogPost
Dim _postTitleUrl As String = String.Empty
Dim _pageGUID As String = String.Empty
Property postTitleUrl() As String
Get
Return _postTitleUrl
End Get
Set(ByVal value As String)
_postTitleUrl = value
End Set
End Property
Property pageGUID() As String
Get
Return _pageGUID
End Get
Set(ByVal value As String)
_pageGUID = value
End Set
End Property
End Class
Now, I have another class where I want to set the values.
现在,我有另一个类,我想在其中设置值。
Public Class SetBlogData
Public blogPostList As New List(Of BlogPost)
Public dataCounter as integer = 0
blogPostList(dataCounter).pageGUID = mainBlogSPWeb.ID.ToString
....
....
This gives me an error about Index was out of range. Hpw can I properly access the properties in BlogPost class?
这给了我一个关于索引超出范围的错误。Hpw 我可以正确访问 BlogPost 类中的属性吗?
回答by shenhengbin
Because your list has nothing .
因为你的清单什么都没有。
You should use add method to add your new item. Like ...
您应该使用 add 方法来添加新项目。喜欢 ...
Dim blogPostList = New List(Of BlogPost)
Dim blogPost = New BlogPost
blogPost.pageGUID = mainBlogSPWeb.ID.ToString
blogPostList.Add(blogPost)
回答by SLaks
You need to put a BlogPost
in your list by writing blogPost.List.Add(New BlogPost())
你需要BlogPost
写一个在你的列表中blogPost.List.Add(New BlogPost())
回答by Adam0787
I find this a good way of inserting into a list:
我发现这是插入列表的好方法:
1) Check if the list is nothing
1) 检查列表是否为空
2) If so instantiate a new list
2) 如果是这样,则实例化一个新列表
3) Add the value to list.
3) 将值添加到列表中。
Below is an example.
下面是一个例子。
Private Sub ExampleAddValueToList(ByVal value as BlogPost)
Try
If _blogPostList Is Nothing Then
_blogPostList = New List(Of BlogPost)
End If
_blogPostList.Add(value)
Catch ex As Exception
debug.write(ex.message)
End Try
End Sub