zxl
/
CTT
forked from Cal/CTT
1
0
Fork 0
CTT/Unity/Assets/Cal/Core/GenericHelper.cs

42 lines
1.5 KiB
C#
Raw Normal View History

2021-04-08 20:09:59 +08:00
using System;
using System.Collections.Generic;
using System.Linq;
namespace ET
{
public static class GenericHelper
{
/// <summary>
/// 判断指定的类型 <paramref name="type"/> 是否是指定泛型类型的子类型,或实现了指定泛型接口。
/// </summary>
/// <param name="type">需要测试的类型。</param>
/// <param name="generic">泛型接口类型,传入 typeof(IXxx&lt;&gt;)</param>
/// <returns>如果是泛型接口的子类型,则返回 true否则返回 false。</returns>
public static bool HasImplementedRawGeneric(this Type type,Type generic)
{
if (type == null) throw new ArgumentNullException(nameof(type));
if (generic == null) throw new ArgumentNullException(nameof(generic));
// 测试接口。
2021-04-11 19:50:39 +08:00
bool isTheRawGenericType = type.GetInterfaces().Any(IsTheRawGenericType);
2021-04-08 20:09:59 +08:00
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);
}
}
}