【问题标题】:How to Convert a character array to string array如何将字符数组转换为字符串数组
【发布时间】:2011-11-28 17:22:27
【问题描述】:

下面的代码要求我将字符数组转换为字符串数组,但出现以下错误: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 使用转换器,但找不到好的示例,我可以使用循环,但认为会有更好的方法。有人可以帮忙吗?

【问题讨论】:

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


    【解决方案1】:

    只需将 lst.AddRange 行更改为:

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

    【讨论】:

      【解决方案2】:

      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
      

      【讨论】:

      • 这也是一个选项。这是 VB 语法: lst.AddRange(Path.GetInvalidPathChars().Select(Function(c) c.ToString())) lst.AddRange(Path.GetInvalidFileNameChars().Select(Function(c) c.ToString() ))
      • @MrShoubs,添加了非 Linq 答案。
      猜你喜欢
      • 2021-12-13
      • 2017-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 1970-01-01
      相关资源
      最近更新 更多