【问题标题】:How to convert ArrayList into string array(string[]) in c#如何在c#中将ArrayList转换为字符串数组(字符串[])
【发布时间】:2012-02-14 01:00:40
【问题描述】:

如何在 C# 中将 ArrayList 转换为 string[]

【问题讨论】:

    标签: c# arrays string arraylist type-conversion


    【解决方案1】:
    string[] myArray = (string[])myarrayList.ToArray(typeof(string));
    

    【讨论】:

    • 我试过这个。我收到以下错误“源数组中的至少一个元素无法转换为目标数组类型”
    • 我知道这已经很晚了,但是您收到该错误的原因是因为您可能有一个 ArrayList 的元素也不是字符串,并且您正在尝试将元素转换为字符串,这没有任何意义
    【解决方案2】:

    使用.ToArray(Type)

    string[] stringArray = (string[])arrayList.ToArray(typeof(string));
    

    【讨论】:

      【解决方案3】:

      一个简单的谷歌或 MSDN 上的搜索就可以完成。这里:

      ArrayList myAL = new ArrayList(); 
      
      // Add stuff to the ArrayList.
      String[] myArr = (String[]) myAL.ToArray( typeof( string ) );
      

      【讨论】:

        【解决方案4】:

        尝试使用ToArray() 方法。

        ArrayList a= new ArrayList(); //your ArrayList object
        var array=(String[])a.ToArray(typeof(string)); // your array!!!
        

        【讨论】:

          【解决方案5】:
          using System.Linq;
          
          public static string[] Convert(this ArrayList items)
          {
              return items == null
                  ? null
                  : items.Cast<object>()
                      .Select(x => x == null ? null : x.ToString())
                      .ToArray();
          }
          

          【讨论】:

          • 我试过这个。但我收到以下错误错误'System.Collections.ArrayList'不包含'Select'的定义并且没有扩展方法'Select'接受'System'类型的第一个参数.Collections.ArrayList' 可以找到(您是否缺少 using 指令或程序集引用?)
          • 您需要在文件顶部包含using System.Linq;。我也错过了.Cast&lt;object&gt;() 电话。
          • 老兄!我的错。我其实以为这样很好,然后急忙按错了按钮!现在是 +1!
          【解决方案6】:

          您可以使用 ArrayList 对象的 CopyTo 方法。

          假设我们有一个数组列表,它的元素是字符串类型。

          strArrayList.CopyTo(strArray)
          

          【讨论】:

            【解决方案7】:

            另一种方式如下。

            System.Collections.ArrayList al = new System.Collections.ArrayList();
            al.Add("1");
            al.Add("2");
            al.Add("3");
            string[] asArr = new string[al.Count];
            al.CopyTo(asArr);
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2012-01-20
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-05-09
              • 1970-01-01
              • 2017-05-20
              相关资源
              最近更新 更多