C# 類型轉換is和as 以及效能陷阱

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   使用   ar   for   2014   

   1.在C#2.0之前,as只能用於參考型別。而在C#2.0之後,它也可以用於可空類型。其結果為可空類型的某個值---空值或者一個有意義的值。
樣本:
 1   static void Main(string[] args) 2         { 3             PrintValueInt32(5); 4             PrintValueInt32("some thing!"); 5     } 6      7       static void PrintValueInt32(object o) 8         { 9             int? nullable = o as int?;10             Console.WriteLine(nullable.HasValue ? nullable.Value.ToString() : "null");11         }
    輸出:

 

  這樣只需要一步,就可以安全的將任意引用轉換為值。而在C#1.0中,你只能先使用is操作符,然後再輕質轉換,這使CLR執行兩次的類型檢查,顯然不夠優雅。

 

 2.我一直以為執行一次的檢查會比兩次快。實際上真的如此嗎?那就來測試一下吧。

 

 1 static void Main(string[] args) 2         {  3             List<object> listobj = new List<object>(); 4             List<int?> list = new List<int?>(); 5  6             for (int i = 0; i < 100000; i++) 7             { 8                 listobj.Add(i); 9             }10 11             Stopwatch watch = new Stopwatch();   //測試時間類12             watch.Start();13             foreach (var item in listobj)14             {15                 if (item is int)                 //is和強型別轉換16                 {17                     list.Add((int)item);18                 }19             }20             watch.Stop();21             Console.WriteLine("is檢查和強型別轉換時間:{0}", watch.Elapsed);22 23             watch.Reset();24             watch.Start();25             foreach (var item in listobj)26             {27                 int? temp = item as int?;        //as轉換和空值判斷,28                 if (temp.HasValue)               //此處也可用temp!=null來判斷29                 {                   //因為temp是可空類型,有HasValue和Value等可用於對可空類型的操作30                     list.Add(temp);31                 }32             }33             watch.Stop();34             Console.WriteLine("as轉換時間:            {0}", watch.Elapsed);35             Console.ReadKey();36         }       

 輸出:

  從輸出的結果看,使用is檢查和強型別轉換時間比as轉換時間少很多。在進行要頻繁在參考型別和實值型別之間轉換的操作時,謹慎選擇,避免掉入效能陷阱。

  3.對於空合并運算子的使用。         

      空合并運算子實在C#2.0中引入的。first??second其執行步驟:        

         (1)對first進行求值。        

         (2)first非空,整個運算式的值就是first的值。        

         (3)否則,求second的值,作為整個運算式的值。

         程式碼範例一,first不為空白時,不管second的值是否為空白,整個運算式的值都是first的值:

 

            int? first = 1;            int? second = 4;            int? temp = first ?? second;            Console.WriteLine("{0}", (temp.HasValue ? temp.Value.ToString() : "null"));

        輸出:(即使second不是空,因為first非空,所以輸出first的值)

      程式碼範例二,first為空白時,second的值整個運算式的值。

 

1             int? first = null;2             int? second = 4;3             int? temp = first ?? second;4             Console.WriteLine("{0}", (temp.HasValue ? temp.Value.ToString() : "null"));

      輸出:

                                                                                                          參考:《深入理解C#》(第三版)  jon steek[英],譯者:姚麒麟

C# 類型轉換is和as 以及效能陷阱

聯繫我們

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