Checking if the object is of same type

前端 未结 4 809
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 07:06

Hello I need to know how to check if the object of the same type in C#.

Scenario:

class Base_Data{}

class Person : Base_Data { }
class Phone  :         


        
4条回答
  •  情话喂你
    2020-12-09 07:54

    It depends on exactly what you're after. Using is or as (as shown in Darin's answer) will tell you if data refers to an instance of Person or a subtype. That's the most common form (although if you can design away from needing it, that would be even better) - and if that's what you need, Darin's answer is the approach to use.

    However, if you need an exact match - if you don't want to take the particular action if data refers to an instance of some class derived from Person, only for Person itself, you'll need something like this:

    if (data.GetType() == typeof(Person))
    

    This is relatively rare - and it's definitely worth questioning your design at this point.

提交回复
热议问题