vb.net 在VB.NET中将字符串数组转换为双数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14054585/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 11:41:26  来源:igfitidea点击:

Convert string array to double array in VB.NET

arraysvb.nettype-conversion

提问by bluebox

I have a string "TextLine" that contains doubles and integers. Now I want to split the string into its parts and convert the resulting string array to double. Unfortunately I get an overload resolution error (for "parse") when I try to do that. What am I doing wrong?

我有一个包含双精度和整数的字符串“TextLine”。现在我想将字符串拆分成它的部分并将结果字符串数组转换为双精度。不幸的是,当我尝试这样做时,我得到了一个重载解析错误(对于“解析”)。我究竟做错了什么?

Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), [Double].Parse)

回答by Steven Doggart

You can do it like this:

你可以这样做:

Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), New Converter(Of String, Double)(AddressOf Double.Parse))

However, if the string array that you are giving it contains any invalid items, that will throw an exception and fail to convert any of the items. If you want to handle invalid items and just default them to 0, you could implement your own converter, like this:

但是,如果您提供给它的字符串数组包含任何无效项目,则会引发异常并且无法转换任何项目。如果您想处理无效项目并将它们默认为 0,您可以实现自己的转换器,如下所示:

Private Function DoubleConverter(ByVal text As String) As Double
    Dim value As Double = 0
    Double.TryParse(text, value)
    Return value
End Function

Then, you can use it like this:

然后,您可以像这样使用它:

Dim doubleAry As Double() = Array.ConvertAll(TextLine.Split(vbTab), New Converter(Of String, Double)(AddressOf DoubleConverter))