【发布时间】:2012-11-15 06:12:39
【问题描述】:
我的类库中的一些函数接受string[] 作为参数。
我想将我的System.Collections.Specialized.StringCollection 转换为string[]。
是否可以使用某个衬垫或者我必须使用循环创建数组?
【问题讨论】:
我的类库中的一些函数接受string[] 作为参数。
我想将我的System.Collections.Specialized.StringCollection 转换为string[]。
是否可以使用某个衬垫或者我必须使用循环创建数组?
【问题讨论】:
使用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);
【讨论】:
试试这个
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<string>().ToArray(); 就足够了。您不必在 ToArray 中再次转换为字符串
.ToArray<string>()和.ToArray()除了输入时的击键次数没有区别。
这就是诀窍:
System.Collections.Specialized.StringCollection sc = new System.Collections.Specialized.StringCollection();
/*sc.Add("A");
sc.Add("B");*/
string[] asArray = sc.Cast<string>().ToArray();
免责声明:我不知道它的性能特点是什么。
【讨论】: