Type Checking: typeof, GetType, or is?

前端 未结 14 2308
北海茫月
北海茫月 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

    Use typeof when you want to get the type at compilation time. Use GetType when you want to get the type at execution time. There are rarely any cases to use is as it does a cast and, in most cases, you end up casting the variable anyway.

    There is a fourth option that you haven't considered (especially if you are going to cast an object to the type you find as well); that is to use as.

    Foo foo = obj as Foo;
    
    if (foo != null)
        // your code here
    

    This only uses one cast whereas this approach:

    if (obj is Foo)
        Foo foo = (Foo)obj;
    

    requires two.

    Update (Jan 2020):

    • As of C# 7+, you can now cast inline, so the 'is' approach can now be done in one cast as well.

    Example:

    if(obj is Foo newLocalFoo)
    {
        // For example, you can now reference 'newLocalFoo' in this local scope
        Console.WriteLine(newLocalFoo);
    }
    

提交回复
热议问题