我希望能够找到特定类型的所有父类型(基类和接口(interface))。
EG 如果我有
class A : B, C { }
class B : D { }
interface C : E { }
class D { }
interface E { }
我想知道 A 是 B C D and E and Object
最好的方法是什么?有没有一种反射(reflection)方法可以做到这一点,或者我需要自己做点什么。
====编辑====
是这样的吗?
public static IEnumerable<Type> ParentTypes(this Type type)
{
foreach (Type i in type.GetInterfaces())
{
yield return i;
foreach (Type t in i.ParentTypes())
{
yield return t;
}
}
if (type.BaseType != null)
{
yield return type.BaseType;
foreach (Type b in type.BaseType.ParentTypes())
{
yield return b;
}
}
}
我有点希望我不必自己做,但是哦,好吧。
最佳答案
更通用的解决方案:
public static bool InheritsFrom(this Type type, Type baseType)
{
// null does not have base type
if (type == null)
{
return false;
}
// only interface or object can have null base type
if (baseType == null)
{
return type.IsInterface || type == typeof(object);
}
// check implemented interfaces
if (baseType.IsInterface)
{
return type.GetInterfaces().Contains(baseType);
}
// check all base types
var currentType = type;
while (currentType != null)
{
if (currentType.BaseType == baseType)
{
return true;
}
currentType = currentType.BaseType;
}
return false;
}
或者实际获取所有父类型:
public static IEnumerable<Type> GetParentTypes(this Type type)
{
// is there any base type?
if (type == null)
{
yield break;
}
// return all implemented or inherited interfaces
foreach (var i in type.GetInterfaces())
{
yield return i;
}
// return all inherited types
var currentBaseType = type.BaseType;
while (currentBaseType != null)
{
yield return currentBaseType;
currentBaseType= currentBaseType.BaseType;
}
}
关于c# - 查找所有父类型(包括基类和接口(interface)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8868119/