How to check if an object is not of a particular type?

前端 未结 7 1731
名媛妹妹
名媛妹妹 2021-01-03 19:38

I want to check if an object is not of a particular type. I know how to check if something is of a particular type:

if (t is TypeA)
{
   ...
}
         


        
7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 19:56

    Short answer: you may want to use:

    if (t.GetType()==typeof(TypeA))
    {
       ...
    }
    if (t.GetType()!=typeof(TypeA))
    {
      ...
    }
    

    Long answer:

    So. Be aware that you're asking if it's a particular type. is doesn't tell you if it's a particular type - it tells you if it's a particular type or any descendant of that type.

    So if you have two classes, Animal, and Cat : Animal, and felix is a cat, then

    if (felix is Animal)
    {
        //returns true
    }
    if (felix.GetType() == typeof(Animal))
    {
        //does not
    }
    

    If it's not important to you, inherited classes are okay, then don't worry about it, use !(felix is Animal) as others mentioned, and you're fine! (You're probably fine.)

    But if you need to be sure felix is specifically an Animal, then you need to ask if t.GetType()==typeof(TypeA).

提交回复
热议问题