C# Object Type Comparison

前端 未结 4 1649
小蘑菇
小蘑菇 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条回答
  •  萌比男神i
    2021-01-30 02:50

    There's a bit of a problem with this idea, though, as every object (and, indeed, every type) DOES have a common base class, Object. What you need to define is how far up the chain of inheritance you want to go (whether it's they're either the same or they have the same immediate parent, or one is the immediate parent of the other, etc.) and do your checks that way. IsAssignableFrom is useful for determining if types are compatible with one another, but won't fully establish if they have the same parent (if that's what you're after).

    If your strict criteria is that the function should return true if...

    • The types are identical
    • One type is the parent (immediate or otherwise) of the other
    • The two types have the same immediate parent

    You could use

    private bool AreSame(Type a, Type b) 
    {
        if(a == b) return true; // Either both are null or they are the same type
    
        if(a == null || b == null) return false; 
    
        if(a.IsSubclassOf(b) || b.IsSubclassOf(a)) return true; // One inherits from the other
    
        return a.BaseType == b.BaseType; // They have the same immediate parent
    }
    

提交回复
热议问题