StringCollection FAQ [C#, BCL] Updated on Monday, March 21, 2005 Written by Allen Lee Q:如何使用StringCollection[1]? A:通常我们有三种方法来访问StringCollection里面的string元素: // Code #01 StringCollection sc = new StringCollection(); sc.AddRange(textBox1.Lines); // StringCollection used together with StringEnumerator. StringEnumerator se = sc.GetEnumerator(); while (se.MoveNext()) { Console.WriteLine(se.Current); } // 'foreach' syntax used. foreach(string str in sc) { Console.WriteLine(str); } // 'for' syntax used. for(int i = 0; i < sc.Count; i++) { Console.WriteLine(sc[i]); } Q:与ArrayList相比,StringCollection有什么优势? A:首先让我们来看看如下代码: // Code #02 // StringCollection used for Strings operation. StringCollection sc = new StringCollection(); sc.AddRange(textBox1.Lines); foreach (string str in sc) { if (str.Trim().StartsWith("File")) { // Do something } else if (str.Trim().StartsWith("Registry")) { // Do something else } } // ArrayList used for Strings operation. ArrayList al = new ArrayList(); al.AddRange(textBox1.Lines); foreach (object obj in al) { string str = (string)obj; if (str.Trim().StartsWith("File")) { // Do something } else if (str.Trim().StartsWith("Registry")) { // Do something else } } 从上面的代码我们看可以看出,用StringCollection写出的代码更加直观(尤其在你要对集合里面的String元素进行复杂的操作的时候),清楚地表明了集合里面的元素的性质,并且免除我们手动进行强类型转换。 Q:StringCollection是否为string作了专门的优化? A:没有!这可能是一个最大的误解,别看到StringCollection只用来储存string就以为它为string的储存作了专门的优化! 虽然在某程度上用StringCollection写的代码比ArrayList的更加直观,然而后者却在性能上稍胜一筹[2]。事实上,StringCollection只是对ArrayList进行了一番装裱而已(以下是使用Reflector反编译的StringCollection代码片断): // Code #03 [Serializable] public class StringCollection : IList, ICollection, IEnumerable { // Methods public void AddRange(string[] value) { if (value == null) { throw new ArgumentNullException("value"); } this.data.AddRange(value); } // Other methods omitted // Properties public string this[int index] { get { return (string) this.data[index]; } set { this.data[index] = value; } } // Other properties omitted // Fields private ArrayList data; } 从代码中我们可以看到StringCollection实质上把其所提供的功能重定向给ArrayList,它们的关系是Use-A。 Q:在什么情况下我们应该使用StringCollection呢? A:这个问题没有标准答案,视你所要处理的问题和你的处理原则而定。首先,让我们来听听Robert B. Murray的想法: 程序的正确性要比它的速度更重要。和人力资源相比,计算机的运行时间的开销会变得越来越便宜;对于那些在提高性能的同时还会导致程序的可理解性和可维护性变差的方法,我们应该持谨慎对待。[3] 于是,一般说来,使用StringCollection而不是ArrayList是有一定作用的。但就我个人来说,我已经习惯了使用ArrayList。当然,如果你使用的是.NET 2.0,那么List会是你不二的选择,它结合了StringCollection和ArrayList的优点——代码直观和性能优良! // Code #04 List<string> ls = new List<string>(); ls.AddRange(textBox1.Lines); foreach (string str in ls) { if (str.Trim().StartsWith("File")) { // Do something } else if (str.Trim().StartsWith("Registry")) { // Do something else } } 本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/diligentcat/archive/2010/04/03/5447042.aspx

评论