1. 程式人生 > >C#為什麼使用AS和IS運算子及其效能比較

C#為什麼使用AS和IS運算子及其效能比較

AS和IS對於如何安全的“向下轉型”提供了較好的解決方案,因此我們有兩種轉型的選擇:

1、使用AS運算子進行型別轉換

2、先使用IS運算子判斷型別是否可以轉換,再使用()運算子進行顯示的轉換

先說AS運算子:

        AS運算子用於在兩個應用型別之間進行轉換,如果轉換失敗則返回null,並不丟擲異常,因此轉換是否成功可以通過結果是否為null進行判斷,並且只有在執行時才能判斷。AS運算子有一定的適用範圍,他只適用於引用型別或可以為null的型別。

IS運算子:

        IS運算子用於檢查物件是否與給定型別相容,並不進行實際的轉換。如果判斷物件引用為null,則返回false。由於僅僅判斷是否相容,因此不會丟擲異常。使用範圍,只適用於引用型別轉換、裝箱轉換和拆箱轉換,而不支援值型別轉換。

在實際工作中儘量使用AS運算子,而少使用()運算子的顯示轉換的理由:

1、無論是AS和IS運算子,都比世界使用()運算子強制轉換更安全。

2、不會丟擲異常,免除使用try···catch進行異常捕獲的必要和系統開銷,只需要判斷是否為null。

3、使用AS比使用IS效能更好(C#4.0權威指南上這麼說),驗證結果如下:第一次執行時有AS時間更短(沒有截圖),但是多執行幾次之後,結果如圖。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace book
{
    class Class1 { }

    class Program
    {
        private Class1 c1 = new Class1();
        static void Main(string[] args)
        {
            Program program = new Program();
            Stopwatch timer = new Stopwatch();
            timer.Start();
            for(int i = 0; i < 100000; i++)
            {
                program.Dosomething1();
            }
            timer.Stop();
            decimal micro = timer.Elapsed.Ticks / 10m;
            Console.WriteLine("IS運算100000次所需時間,{0:F1}微秒",micro);

            timer = new Stopwatch();
            timer.Start();
            for(int i = 0; i < 100000; i++)
            {
                program.Dosomething2();
            }
            timer.Stop();
            micro = timer.Elapsed.Ticks/10m;
            Console.WriteLine("AS運算100000次所需時間,{0:F1}微秒",micro);
            Console.ReadKey();
        }
        public void Dosomething1()
        {
            object c2 = c1;
            if(c2 is Class1)
            {
                Class1 c = (Class1)c2;
            }
        }
        public void Dosomething2()
        {
            object c2 = c1;
            Class1 c = c2 as Class1;
            if (c != null)
            {

            }
        }
    }
}
第三次 第四次