Type Checking: typeof, GetType, or is?

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

    1.

    Type t = typeof(obj1);
    if (t == typeof(int))
    

    This is illegal, because typeof only works on types, not on variables. I assume obj1 is a variable. So, in this way typeof is static, and does its work at compile time instead of runtime.

    2.

    if (obj1.GetType() == typeof(int))
    

    This is true if obj1 is exactly of type int. If obj1 derives from int, the if condition will be false.

    3.

    if (obj1 is int)
    

    This is true if obj1 is an int, or if it derives from a class called int, or if it implements an interface called int.

提交回复
热议问题