Type Checking: typeof, GetType, or is?

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

    I prefer is

    That said, if you're using is, you're likely not using inheritance properly.

    Assume that Person : Entity, and that Animal : Entity. Feed is a virtual method in Entity (to make Neil happy)

    class Person
    {
      // A Person should be able to Feed
      // another Entity, but they way he feeds
      // each is different
      public override void Feed( Entity e )
      {
        if( e is Person )
        {
          // feed me
        }
        else if( e is Animal )
        {
          // ruff
        }
      }
    }
    

    Rather

    class Person
    {
      public override void Feed( Person p )
      {
        // feed the person
      }
      public override void Feed( Animal a )
      {
        // feed the animal
      }
    }
    

提交回复
热议问题