添加到数组
我有一个数组:
String[] ay = {
"blah",
"blah number 2"
"etc" };
...但现在我想稍后添加到这个数组中,但我看不到这样做的选项。这怎么能做到呢?我不断收到一条消息,说字符串无法转换为 String[]。
谢谢
I have an array:
String[] ay = {
"blah",
"blah number 2"
"etc" };
... But now I want to add to this array at a later time, but I see no option to do so. How can this be done? I keep getting a message saying that the String cannot be converted to String[].
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
使用列表而不是数组:
然后,如果您确实需要它作为数组:
Use a List rather than an array:
Then, later, if you really do need it as an array:
数组的大小是固定的,因此创建后就无法更改其大小(无需创建新的数组对象),
请使用
List
代替数组。Arrays are of fixed size, so after it has been created, you can't change the size of it (without creating a new array object)
Use the
List<string>
instead of the array.数组在声明后就无法更改其大小。请改用集合。例如:
列表
。Arrays can't change their size after they are declared. Use collections instead. For example:
List
.正如大家已经说过的,在 System.Collections.Generic 命名空间中使用 List。
您还可以使用哈希表,它允许您为每个字符串赋予含义,或者使用“键”,它为您提供一种简单的方法来使用关键字提取特定字符串。 (至于出于任何目的将消息存储在内存空间中。)
您还可以每次添加值时创建一个新数组,使新数组比旧数组大 1,将第一个数组中的所有数据复制到第二个数组中,然后在最后一个槽中添加新值(长度- 1)
然后用新阵列替换旧阵列。
这是最手动的方法。
但 List 和 Hashtable 也能很好地工作。
As everyone's already said, use List in the System.Collections.Generic namespace.
You could also use a Hashtable which will allow you to give each string a meaning, or "key" which gives you an easy way to pull out a certain string with a keyword. (as for keeping messages stored in memory space for whatever purpose.)
You could also Create a new array each time you add a value, make the new array 1 bigger than the old one, copy all the data from the first array into the 2nd array, and then add your new value in the last slot (Length - 1)
Then replace the old array with your new one.
It's the most manual way of doing it.
But List and Hashtable work perfectly well too.
如果您不需要索引特定的数组元素(使用括号),但希望能够有效地添加或删除元素,则可以使用 LinkedList。
If you don't need indexing a specific array element (usage of brackets), but you want to be able to efficiently add or remove elements, you could use LinkedList.
如果您确实需要索引
查看 System.Collection 中的字典数据类型
http://msdn .microsoft.com/en-us/library/xfhwa508.aspx
所以你可以做类似的事情
If you do need indexing
have a look at Dictionary data type also in the System.Collection
http://msdn.microsoft.com/en-us/library/xfhwa508.aspx
so you could do something like
你可以这样做,但我不推荐这样做:
}
You can do this but I don't recommend it:
}
这是一个扩展方法,用于将数组添加在一起并创建一个新的字符串数组
Here's an extension method to add the to arrays together and create a new string array