StringCollection FAQ [C#, BCL]

來源:互聯網
上載者:User

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

Liststring> ls = new Liststring>();
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
    }
}

關於這個問題,我也請教了Kit George:

Kit,

Hi, I'm Allen Lee. I want to ask you in what situations we shall use System.Collection.Specialized.StringCollection? When I used Reflector to deassembly .NET, I found that StringCollection actually uses a ArrayList to provide its functions and it doesn't have a better performance than ArrayList! What's more, in .NET 2.0, we have generics; then is it necessary to use StringCollection or leave it alone in our future development?

I'm looking forward to hearing from you! Thanks!

Yours, sincerely
Allen Lee
Friday, March 18, 2005

Allen: leave it alone, and use List. StringCollection should probably be avoided now we have generics.

可見,在.NET 2.0中,泛型集合類應該作為我們處理這類問題的首選工具。如果你對使用泛型集合類感興趣的話,可以看看《Power Collections - An Extension Library for System.Collections.Generic》這個MSDN TV。

 

  • [1] 該集合類位於System.Collections.Specialized命名空間。
  • [2] 關於StringCollection和ArrayList的效能比較,可以參考aierong的文章。
  • [3] [美]Robert B. Murray 著;王昕 譯;《C++ 編程慣用法——進階程式員常用方法和技巧》;中國電力出版社,2004

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.