Type Checking: typeof, GetType, or is?

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

    I had a Type-property to compare to and could not use is (like my_type is _BaseTypetoLookFor), but I could use these:

    base_type.IsInstanceOfType(derived_object);
    base_type.IsAssignableFrom(derived_type);
    derived_type.IsSubClassOf(base_type);
    

    Notice that IsInstanceOfType and IsAssignableFrom return true when comparing the same types, where IsSubClassOf will return false. And IsSubclassOf does not work on interfaces, where the other two do. (See also this question and answer.)

    public class Animal {}
    public interface ITrainable {}
    public class Dog : Animal, ITrainable{}
    
    Animal dog = new Dog();
    
    typeof(Animal).IsInstanceOfType(dog);     // true
    typeof(Dog).IsInstanceOfType(dog);        // true
    typeof(ITrainable).IsInstanceOfType(dog); // true
    
    typeof(Animal).IsAssignableFrom(dog.GetType());      // true
    typeof(Dog).IsAssignableFrom(dog.GetType());         // true
    typeof(ITrainable).IsAssignableFrom(dog.GetType()); // true
    
    dog.GetType().IsSubclassOf(typeof(Animal));            // true
    dog.GetType().IsSubclassOf(typeof(Dog));               // false
    dog.GetType().IsSubclassOf(typeof(ITrainable)); // false
    

提交回复
热议问题