Checking if the object is of same type

前端 未结 4 806
没有蜡笔的小新
没有蜡笔的小新 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:49

    You could use the is operator:

    if (data is Person)
    {
        // `data` is an instance of Person
    }
    

    Another possibility is to use the as operator:

    var person = data as Person;
    if (person != null)
    {
        // safely use `person` here
    }
    

    Or, starting with C# 7, use a pattern-matching form of the is operator that combines the above two:

    if (data is Person person)
    {
        // `data` is an instance of Person,
        // and you can use it as such through `person`.
    }
    

提交回复
热议问题