is vs typeof

前端 未结 4 1931
遇见更好的自我
遇见更好的自我 2020-11-30 19:28

Which of these pieces of code is faster?

if (obj is ClassA) {}

if (obj.GetType() == typeof(ClassA)) {}

Edit: I\'m aware that they don\'t d

4条回答
  •  日久生厌
    2020-11-30 20:14

    They don't do the same thing. The first one works if obj is of type ClassA or of some subclass of ClassA. The second one will only match objects of type ClassA. The second one will be faster since it doesn't have to check the class hierarchy.

    For those who want to know the reason, but don't want to read the article referenced in is vs typeof.

提交回复
热议问题