vb.net 清除字符串数组的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/713867/
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
What is the best way to clear an array of strings?
提问by spacemonkeys
What is the best way to clear an array of strings?
清除字符串数组的最佳方法是什么?
回答by Micah
Wrong way:
错误的方法:
myArray = Nothing
Only sets the variable pointing to the array to nothing, but doesn't actually clear the array. Any other variables pointing to the same array will still hold the value. Therefore it is necessary to clear out the array.
只将指向数组的变量设置为空,但实际上并不清除数组。指向同一数组的任何其他变量仍将保留该值。因此有必要清除阵列。
Correct Way
正确方式
Array.Clear(myArray,0,myArray.Length)
回答by Dustin Campbell
And of course there's the VB way using the Erase keyword:
当然还有使用 Erase 关键字的 VB 方式:
Dim arr() as String = {"a","b","c"}
Erase arr
回答by Richard
Depending what you want:
取决于你想要什么:
- Assign Nothing (null)
- Assign a new (empty) array
- Array.Clear
- 不分配任何内容(空)
- 分配一个新的(空)数组
- 数组.清除
Last is likely to be slowest, but only option if you don't want a new array.
最后可能是最慢的,但只有在您不想要新阵列时才可以选择。
回答by Joel Coehoorn
If you're needing to do things like clear, you probably want a collectionlike List(Of String)
rather than an array.
如果您需要执行诸如清除之类的操作,您可能需要一个类似集合List(Of String)
而不是数组。
回答by Steve Honne
redim arr(1,1,1,1) and then redim (z,x,y,v) to your dimensions
redim arr(1,1,1,1) 然后 redim (z,x,y,v) 到您的尺寸
回答by Wolfgang Grinfeld
If you need to reinitialize with empty strings or other values not equal to Nothing/Null, you may get further using an extension method:
如果您需要使用空字符串或其他不等于 Nothing/Null 的值重新初始化,您可以使用扩展方法进一步获得:
Option Strict On : Option Explicit On : Option Infer On
...
Public Delegate Sub ArrayForAllDelegate(Of T)(ByRef message As T)
<Extension>
Public Function ForAll(Of T)(ByRef self As T(), f As ArrayForAllDelegate(Of T)) As T()
Dim i = 0
While i < self.Length
f(self(i))
i += 1
End While
Return self
End Function
Then your initialization code:
然后你的初始化代码:
Dim a = New String(3 - 1) {"a", "b", "c"}
...
a.ForAll(Sub(ByRef el) el = "") 'reinitialize the array with actual empty strings