确定类型是否为枚举类型的泛型列表

本文关键字:类型 泛型 枚举 列表 是否 | 更新日期: 2023-09-27 18:36:05

我需要确定给定类型是否是枚举类型的通用列表。

我想出了以下代码:

void Main()
{
    TestIfListOfEnum(typeof(int));
    TestIfListOfEnum(typeof(DayOfWeek[]));
    TestIfListOfEnum(typeof(List<int>));
    TestIfListOfEnum(typeof(List<DayOfWeek>));
    TestIfListOfEnum(typeof(List<DayOfWeek>));
    TestIfListOfEnum(typeof(IEnumerable<DayOfWeek>));
}
void TestIfListOfEnum(Type type)
{
    Console.WriteLine("Object Type: '"{0}'", List of Enum: {1}", type, IsListOfEnum(type));
}
bool IsListOfEnum(Type type)
{
    var itemInfo = type.GetProperty("Item");
    return (itemInfo != null) ? itemInfo.PropertyType.IsEnum : false;
}

下面是上面代码的输出:

Object Type: "System.Int32", List of Enum: False
Object Type: "System.DayOfWeek[]", List of Enum: False
Object Type: "System.Collections.Generic.List`1[System.Int32]", List of Enum: False
Object Type: "System.Collections.Generic.List`1[System.DayOfWeek]", List of Enum: True
Object Type: "System.Collections.Generic.List`1[System.DayOfWeek]", List of Enum: True
Object Type: "System.Collections.Generic.IEnumerable`1[System.DayOfWeek]", List of Enum: False

除了最后一个示例之外,所有输出都正是我想要的。它不会检测到typeof(IEnumerable<DayOfWeek>)是枚举类型的集合。

有谁知道我如何检测最后一个示例中的枚举类型?

确定类型是否为枚举类型的泛型列表

如果要

测试它,给定一个类型,则它是IEnumerable<T>类型,其中Tenum,您可以执行以下操作。

首先,获取可枚举枚举所基于的类型的方法:

    public static IEnumerable<Type> GetEnumerableTypes(Type type)
    {
        if (type.IsInterface)
        {
            if (type.IsGenericType
                && type.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                yield return type.GetGenericArguments()[0];
            }
        }
        foreach (Type intType in type.GetInterfaces())
        {
            if (intType.IsGenericType
                && intType.GetGenericTypeDefinition() == typeof(IEnumerable<>))
            {
                yield return intType.GetGenericArguments()[0];
            }
        }
    }

然后:

    public static bool IsEnumerableOfEnum(Type type)
    {
        return GetEnumerableTypes(type).Any(t => t.IsEnum);
    }

您可以像这样获取IEnumerable<T>的类型:

Type enumerableType = enumerable.GetType().GenericTypeArguments[0];

然后,您可以通过检查该类型是否可以分配给类型Enum(枚举的基类)的变量来测试它是否是枚举:

typeof(Enum).IsAssignableFrom(enumerableType)

这是一个简单的方法:

public static bool TestIfSequenceOfEnum(Type type)
{
    return (type.IsInterface ? new[] { type } : type.GetInterfaces())
        .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IEnumerable<>))
        .Any(i => i.GetGenericArguments().First().IsEnum);
}

基本上,提取该类型实现的所有接口,找到所有IEnumerable<T>并返回true如果这些T中的任何一个是枚举。请记住,一个具体的类可能会实现多次IEnumerable<T>(使用不同的T)。

如果type是一个类或它是一个接口,这都有效。