C# 检查System.Type是否为给定类的后代的最佳方法
考虑以下代码:C# 检查System.Type是否为给定类的后代的最佳方法,c#,.net,reflection,type-systems,system.type,C#,.net,Reflection,Type Systems,System.type,考虑以下代码: 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() {
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());
}
}
实现IsDescendatof的最佳方法是什么?您可能正在寻找。确定当前类型表示的类是否派生自指定类型表示的类。我想您正在寻找这个 编辑: 我不知道您的要求,但这可能是最好的方式:
bool isDescendant = cValue is C;
<>我意识到这并不能直接回答你的问题,但是你可以考虑用这个代替你例子中的方法:
public static bool IsDescendantOf<T>(this object o)
{
if(o == null) throw new ArgumentNullException();
return typeof(T).IsSubclassOf(o.GetType());
}
然后,typeof(A).IsAssignableFrom(b.GetType())
为真-因此A可能是b的子类,或者是接口类型
相反,
a.GetType().IsSubclassOf(typeof(B))
仅当a是B的子类时才会返回true。鉴于扩展方法的名称,我建议您应该使用IsSubclassOf,而不是IsAssignable to 嗯。。。这也应该很有效。现在我很好奇Type.IsAssignableFrom和Type.IsSubclassOf?type1.IsAssignableFrom(type2)之间有什么区别,如果type1是一个接口,那么它就可以工作了。我想那类型。IsSubclassOf()更像我要找的类型。:)谢谢……’因为在我的案例系统中。类型只能是一个类。@SH0G您的最后一段第二段是否正确?我认为如果a=b,那么a.GetType().IsAssignableFrom(typeof(b))
将为真代码>有效。这很有用,但如果两种类型相同,它将返回true
。赋值兼容性和继承之间存在一些差异。我还发现它比IsSubClassOf
更难阅读。
C c = new C();
c.IsDescendantOf<A>();
a = b;