C# Object Type Comparison

前端 未结 4 1695
小蘑菇
小蘑菇 2021-01-30 02:04

How can I compare the types of two objects declared as type.

I want to know if two objects are of the same type or from the same base class.

Any help is apprecia

4条回答
  •  天命终不由人
    2021-01-30 02:53

    Say a and b are the two objects. If you want to see if a and b are in the same inheritance hierarchy, then use Type.IsAssignableFrom:

    var t = a.GetType();
    var u = b.GetType();
    
    if (t.IsAssignableFrom(u) || u.IsAssignableFrom(t)) {
      // x.IsAssignableFrom(y) returns true if:
      //   (1) x and y are the same type
      //   (2) x and y are in the same inheritance hierarchy
      //   (3) y is implemented by x
      //   (4) y is a generic type parameter and one of its constraints is x
    }
    

    If you want to check if one is a base class of the other, then try Type.IsSubclassOf.

    If you know the specific base class, then just use the is keyword:

    if (a is T && b is T) {
      // Objects are both of type T.
    }
    

    Otherwise, you'll have to walk the inheritance hierarchy directly.

提交回复
热议问题