在 VB.Net 中创建时将项目添加到列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2628223/
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
Adding items to the List at creation time in VB.Net
提问by Shaddix
In c# I can initialize a List at creation time like
在 c# 中,我可以在创建时初始化一个列表,例如
var list = new List<String>() {"string1", "string2"};
is there a similar thing in VB.Net? Currently I can do it like
VB.Net 中有类似的东西吗?目前我可以这样做
Dim list As New List(Of String)
list.Add("string1")
list.Add("string2")
list.Add("string3")
but I want to avoid boring .Add lines
但我想避免无聊。添加行
回答by Jon Skeet
VB10 supports collection initializers. I believe your example would be:
VB10 支持集合初始值设定项。我相信你的例子是:
Dim list As New List(Of String) From { "string1", "string2", "string3" }
回答by John
You can also use AddRange if you don't want to put all of your items on a single line.
如果您不想将所有项目放在一行中,也可以使用 AddRange。
Dim list As New List(Of String) From { "string1", "string2", "string3" }
list.addRange({"string4", "string5", "string6"})
回答by Hans Olsson
Dim a As New List(Of String)(New String() {"str1", "str2"})
Though if it's VB 2010 I'd definitely go with Jon Skeet's answer.
虽然如果是 VB 2010,我肯定会选择 Jon Skeet 的答案。