asp.net c# string[], int[]數組用法與區別

來源:互聯網
上載者:User

經常用string[], int[]這些數組, 今天偶然發現還有一個System.Array類, 它的聲明如下:

 代碼如下 複製代碼

public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable

看來它是一個抽象類別.

查一下msdn, 發現它的用途如下:

"提供建立、操作、搜尋和排序數組的方法,因而在通用語言執行平台中用作所有數組的基類。"
"Array 類是支援數組的語言實現的基類。但是,只有系統和編譯器能夠從 Array 類顯式派生。使用者應當使用由語言提供的數組構造。"

自己寫代碼試了一下, 確實如上所述, 不能繼承Array這個抽象類別,

 

Array的使用方法舉例:

 代碼如下 複製代碼

            Array abc = Array.CreateInstance(typeof(string), 3);
            abc.SetValue("lzd1", 0);
            abc.SetValue("lzd2", 1);
            abc.SetValue("lzd3", 2);
            for (int i = 0; i < abc.Length; i++)
            {
                Console.WriteLine(abc.GetValue(i));
            }

看這代碼,覺得和string[], int[]的本質是一樣的,就是繁瑣些,難怪msdn說它是所有數組的基類,但是用refactor翻譯一段string[],int[]的代碼,發現編譯後並不翻譯成Array,不知道內部它們之間是怎麼轉換的,先不管這也罷,反正最重要的思考一下Array的作用和用途在哪裡?畢竟直接定義的數組比Array.CreateInstance()要簡單得多。

 

試一下就可以明白,直接定義的數組不支援排序等操作,如果定義了string[], int[],想要排序,就可以用Array抽象類別中的Sort方法了,我想,這是它很有用的一點了。

        

 代碼如下 複製代碼
    string[] def = new string[] { "lzd7", "lzd5", "lzd6" };
            for (int i = 0; i < def.Length; i++)
            {
                Console.WriteLine(def[i]);
            }
            Array.Sort(def);
            for (int i = 0; i < def.Length; i++)
            {
                Console.WriteLine(def[i]);
            }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.