Type Checking: typeof, GetType, or is?

前端 未结 14 2265
北海茫月
北海茫月 2020-11-22 00:49

I\'ve seen many people use the following code:

Type t = typeof(obj1);
if (t == typeof(int))
    // Some code here

But I know you could also

相关标签:
14条回答
  • 2020-11-22 01:30

    Performance test typeof() vs GetType():

    using System;
    namespace ConsoleApplication1
        {
        class Program
        {
            enum TestEnum { E1, E2, E3 }
            static void Main(string[] args)
            {
                {
                    var start = DateTime.UtcNow;
                    for (var i = 0; i < 1000000000; i++)
                        Test1(TestEnum.E2);
                    Console.WriteLine(DateTime.UtcNow - start);
                }
                {
                    var start = DateTime.UtcNow;
                    for (var i = 0; i < 1000000000; i++)
                        Test2(TestEnum.E2);
                    Console.WriteLine(DateTime.UtcNow - start);
                }
                Console.ReadLine();
            }
            static Type Test1<T>(T value) => typeof(T);
            static Type Test2(object value) => value.GetType();
        }
    }
    

    Results in debug mode:

    00:00:08.4096636
    00:00:10.8570657
    

    Results in release mode:

    00:00:02.3799048
    00:00:07.1797128
    
    0 讨论(0)
  • 2020-11-22 01:33

    I believe the last one also looks at inheritance (e.g. Dog is Animal == true), which is better in most cases.

    0 讨论(0)
提交回复
热议问题