简体   繁体   中英

Best way to check if System.Type is a descendant of a given class

Consider the following code:

public class A 
{
}  

public class B : A 
{
}  

public class C : B 
{
}  

class D  
{  
    public static bool IsDescendantOf(this System.Type thisType, System.Type thatType)  
    {  
        /// ??? 
    } 

    void Main()
    {
        A cValue = new C();
        C.GetType().IsDescendantOf(cValue.GetType());
    }
}

What is the best way to implement IsDescendantOf?

Type.IsSubclassOf()确定当前Type所表示的类是否派生自指定Type所表示的类。

您可能正在寻找Type.IsAssignableFrom

I realise this doesn't directly answer your question, but you might consider using this instead of the method in your example:

public static bool IsDescendantOf<T>(this object o)
{
    if(o == null) throw new ArgumentNullException();
    return typeof(T).IsSubclassOf(o.GetType());
}

So you can use it like this:

C c = new C();
c.IsDescendantOf<A>();

Also, to answer your question about the difference between Type.IsSubclassOf and Type.IsAssignableFrom - IsAssignableFrom is weaker in the sense that if you have two objects a and b such that this is valid:

a = b;

Then typeof(A).IsAssignableFrom(b.GetType()) is true - so a could be a subclass of b, or an interface type.

In contrast, a.GetType().IsSubclassOf(typeof(B)) would only return true if a were a subclass of b. Given the name of your extension method, I'd say you should use IsSubclassOf instead of IsAssignable to;

I think you are looking for this Type.IsSubclassOf()

Edit:

I don't know your requirements but may be thats the best way:

bool isDescendant = cValue is C;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM