答案 0 :(得分:3)
答案 1 :(得分:1)
答案 2 :(得分:1)
答案 3 :(得分:0)
除了接口之外,我还需要对此进行扩展以包含类型继承。这就是我想出的:
interface IFace<T> {}
class Impl<T> : IFace<T> {}
class Derived<T> : Impl<T> {}
public static bool InheritsFrom(this Type tDerived, Type tBase)
{
if (tDerived.IsSubtypeOf(tBase)) return true;
var interfaces = tDerived.GetInterfaces()
.Select(i => i.IsGenericType ? i.GetGenericTypeDefinition() : i);
return interfaces.Contains(tBase);
}
public static bool IsSubtypeOf(this Type tDerived, Type tBase)
{
var currentType = tDerived.BaseType;
while (currentType != null)
{
if (currentType.IsGenericType)
currentType = currentType.GetGenericTypeDefinition();
if (currentType == tBase) return true;
currentType = currentType.BaseType;
}
return false;
}
请注意,虽然这些方法适用于任何两种类型,但它们假设如果传递泛型类型,则类型是开放的(即,它是没有定义类型参数的泛型类型定义)。