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

为君一笑 提交于 2019-12-06 17:19:07

问题


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?


回答1:


Type.IsSubclassOf() Determines whether the class represented by the current Type derives from the class represented by the specified Type.




回答2:


You are probably looking for Type.IsAssignableFrom.




回答3:


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;




回答4:


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;


来源:https://stackoverflow.com/questions/1433750/best-way-to-check-if-system-type-is-a-descendant-of-a-given-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!