如何将字符数组转换为字符串数组

时间:2011-11-28 17:22:27

标签: vb.net .net-2.0 type-conversion converter

我有下面的代码要求我将字符数组转换为字符串数组,但是我收到以下错误:Option Strict On disallows implicit conversions from '1-dimensional array of Char' to 'System.Collections.Generic.IEnumerable(Of String)'

    Dim lst As New List(Of String)
    lst.AddRange(IO.Path.GetInvalidPathChars())
    lst.AddRange(IO.Path.GetInvalidFileNameChars())

    lst.Add("&")
    lst.Add("-")
    lst.Add(" ")

    Dim sbNewName As New StringBuilder(orignalName)
    For i As Integer = 0 To lst.Count - 1
        sbNewName.Replace(lst(i), "_")
    Next

    Return sbNewName.ToString

我尝试通过Array.ConvertAll使用转换器,但找不到一个好例子,我可以使用循环,但认为会有更好的方法。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:2)

只需将lst.AddRange行更改为:

Array.ForEach(Path.GetInvalidPathChars(), AddressOf lst.Add)
Array.ForEach(Path.GetInvalidFileNameChars(), AddressOf lst.Add)

答案 1 :(得分:1)

VB Linq语法对我来说不是一个强项,但为了让您入门,请考虑从字符数组中选择项目并将每个项目转换为字符串。在C#中,那将是

lst.AddRange(System.IO.Path.GetInvalidPathChars().Select(c => c.ToString()); 

感谢NYSystemsAnalyst的VB语法

lst.AddRange(System.IO.Path.GetInvalidPathChars().Select(Function(c) c.ToString()))

如果没有Linq,你可以简单地在循环中迭代

For Each c as Char in System.IO.Path.GetInvalidPathChars()
    lst.Add(c.ToString())
Next c