请考虑以下代码:

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());
    }
}

实施IsDescendantOf的最佳方法是什么?

有帮助吗?

解决方案

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

其他提示

您可能正在寻找 Type.IsAssignableFrom

我意识到这并没有直接回答你的问题,但你可以考虑使用它而不是你的例子中的方法:

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

所以你可以像这样使用它:

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

另外,要回答关于Type.IsSubclassOf和Type.IsAssignableFrom之间区别的问题 - IsAssignableFrom在某种意义上是较弱的,如果你有两个对象a和b,这是有效的:

a = b;

然后 typeof(A).IsAssignableFrom(b.GetType())为真 - 所以a可以是b的子类,或者是接口类型。

相反, a.GetType()。IsSubclassOf(typeof(B))只有在a是b的子类时才返回true。鉴于你的扩展方法的名称,我会说你应该使用IsSubclassOf代替IsAssignable;

我认为您正在寻找这个 Type.IsSubclassOf( )

编辑:

我不知道你的要求,但可能是最好的方式:

bool isDescendant = cValue is C;
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top