【问题标题】:How to convert type System.Collections.Specialized.StringCollection to string[]如何将 System.Collections.Specialized.StringCollection 类型转换为字符串 []
【发布时间】:2012-11-15 06:12:39
【问题描述】:

我的类库中的一些函数接受string[] 作为参数。

我想将我的System.Collections.Specialized.StringCollection 转换为string[]

是否可以使用某个衬垫或者我必须使用循环创建数组?

【问题讨论】:

    标签: c# c#-4.0


    【解决方案1】:

    使用StringCollection.CopyTo(string[],index) 将内容复制到字符串数组。 所有 .Net 框架都支持此功能。

    System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
    sc.Add("Test");
    sc.Add("Test2");
    
    string[] strArray = new string[sc.Count];
    sc.CopyTo(strArray,0);
    

    【讨论】:

      【解决方案2】:

      试试这个

      System.Collections.Specialized.StringCollection strs = new  System.Collections.Specialized.StringCollection();
      strs.Add("blah"); 
      strs.Add("blah"); 
      strs.Add("blah"); 
      
      string[] strArr = strs.Cast<string>().ToArray<string>();
      

      【讨论】:

      • strs.Cast&lt;string&gt;().ToArray(); 就足够了。您不必在 ToArray 中再次转换为字符串
      • @Habib:.ToArray&lt;string&gt;().ToArray()除了输入时的击键次数没有区别。
      【解决方案3】:

      这就是诀窍:

      System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
      /*sc.Add("A");
      sc.Add("B");*/
      string[] asArray = sc.Cast<string>().ToArray();
      

      免责声明:我不知道它的性能特点是什么。

      【讨论】:

        猜你喜欢
        • 2012-09-19
        • 1970-01-01
        • 2022-08-18
        • 2019-09-10
        • 1970-01-01
        • 2019-01-21
        • 2016-12-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多