.NET/C#如何判断某个类是否是泛型类型或泛型接口的子类型详解

2019-05-25 11:11:25王旭

于是,我们可以把这两个方法合成一个,用于实现类似 IsAssignableFrom 的效果,不过这回将支持原始接口(也就是 typeof(Foo<>) )。

/// <summary>
/// 判断指定的类型 <paramref name="type"/> 是否是指定泛型类型的子类型,或实现了指定泛型接口。
/// </summary>
/// <param name="type">需要测试的类型。</param>
/// <param name="generic">泛型接口类型,传入 typeof(IXxx<>)</param>
/// <returns>如果是泛型接口的子类型,则返回 true,否则返回 false。</returns>
public static bool HasImplementedRawGeneric([NotNull] this Type type, [NotNull] Type generic)
{
 if (type == null) throw new ArgumentNullException(nameof(type));
 if (generic == null) throw new ArgumentNullException(nameof(generic));

 // 测试接口。
 var isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
 if (isTheRawGenericType) return true;

 // 测试类型。
 while (type != null && type != typeof(object))
 {
 isTheRawGenericType = IsTheRawGenericType(type);
 if (isTheRawGenericType) return true;
 type = type.BaseType;
 }

 // 没有找到任何匹配的接口或类型。
 return false;

 // 测试某个类型是否是指定的原始接口。
 bool IsTheRawGenericType(Type test)
 => generic == (test.IsGenericType ? test.GetGenericTypeDefinition() : test);
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对易采站长站的支持。