類型轉換總結

來源:互聯網
上載者:User

標籤:類型轉換   tryparse   as   

1、將任意類型轉化成字串類型

       ToString();

2、將字串類型轉換成任意類型

       Parse()或者TryParse(),重點說一下TryParse(),先看執行個體,瞭解TryParse()的用法

//使用TryParse()進行類型轉換string tryStr = "10aa";int result;bool b = int.TryParse(tryStr, out result);if (b){    Console.WriteLine("類型轉換成功");    Console.WriteLine(result);}else{    Console.WriteLine("轉換失敗");    Console.WriteLine(result);}Console.ReadKey();

        如果運行這段代碼,返回值是:

            轉換失敗

           0

        如果這個地方用Parse()代替,如執行個體:

string Str = "10aa";Console.WriteLine(int.Parse(Str));//如果不能轉換則會報錯
        通過編譯,代碼會報錯,通過比較,我們很清楚的看出,TryParse()比Parse()有明顯的優勢,在轉換是否成功時,做出不一樣的處理。

       補充:將字串類型轉換成枚舉類型

        我們先聲明一個枚舉類型

//不是繼承了byte類型,而是限制枚舉的值屬於byte的範圍public enum UserState : byte{    Qme,    Online = 253,    Hide,    Busy}
        接下看字串"Qme"是怎麼轉換成枚舉的:

//先說明一下GetType()與typeof()的區別。假如//Int32 i = new Int32(); //i.GetType()傳回值是Int32的類型,但是無法使用typeof(i),因為i是一個變數,//如果要使用typeof(),則只能:typeof(Int32),返回的同樣是Int32的類型。//將字串類型轉化成枚舉類型。string qme = "Qme";UserState state = (UserState)Enum.Parse(typeof(UserState), qme);Console.WriteLine((int)state);Console.ReadKey();
        返回值為0

3、將任意類型轉化成任意類型

       Convert();

4、類與類之間轉換

#region 類型轉換一(用一對()實現轉換)Person p = new Chinese();p.Name = "Lrh";if (p is Chinese) //判斷一個對象是否屬於某個類型{    Chinese chin = (Chinese)p;    Console.WriteLine(chin.Name);}else{    Console.WriteLine("強制類型轉換失敗");}Console.ReadKey();#endregion
#region 類型轉換二(用as實現轉換)Person p = new Person();//此種轉換寫法會異常//Chinese ch = (Chinese)p;//用as進行轉換時,如果轉換失敗也不會報異常,只是會返回NullChinese ch = p as Chinese;//推薦使用as類型轉換Console.WriteLine(ch.China);Console.ReadKey();#endregion

5、隱式類型轉換與顯示類型轉換(簡單一實例)

Chinese ch = new Chinese();ch.China = "中國";//把子類類型轉換成父類類型,發生了隱式轉換Person p = ch;//把父類類型轉化成子類類型,需要顯示類型轉換Chinese c = (Chinese)p;Console.WriteLine(c.China);Console.ReadKey();


補充Person類和Chinese類之間的關係

class Person    {        public string Name        {            get;            set;        }    }    class Chinese:Person    {        public string China        {            get;            set;        }    }



類型轉換總結

聯繫我們

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