如何将System.Collections.Specialized.StringCollection类型转换为string []

Ann*_*nie 22 c# c#-4.0

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

我想把我转换System.Collections.Specialized.StringCollection成string[].

是否有可能使用一个衬垫或我必须创建带循环的数组?

Hab*_*bib 29

使用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);
Run Code Online (Sandbox Code Playgroud)


yog*_*ogi 28

试试这个

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>();
Run Code Online (Sandbox Code Playgroud)

  • `strs.Cast <string>().ToArray();`就够了.您不必在`ToArray`中再次强制转换为字符串 (9认同)

sya*_*ani 8

这样做的诀窍:

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

免责声明:我不知道这是什么性能特征.